выберите раскрывающееся значение по умолчанию первого индекса массива angular 7 сафари - PullRequest
1 голос
/ 07 февраля 2020

Я использую Safari и пытаюсь сделать массив первым индексом в качестве опции по умолчанию в выпадающем списке select, но почему-то он не показывает никакой опции по умолчанию. я не хочу обрабатывать это на стороне кода, так как некоторые значения могут поступать от сервисов.

Я пытался selected = "selected", но без помощи.

Есть ли способ, которым мы можем сделать вариант по умолчанию напрямую? или вручную?

ниже мой код и стекаблиц.

https://stackblitz.com/edit/angular-7aqzj2

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    constructor(
        public form: FormBuilder
    ) {}
    name = 'Angular 5';
    selectedCountry: any;
    public dropdown: FormGroup;
    countrydrodown = [];
    cities = {};
    places = {};
    texts = {};
    countriesValue = [{
        'id': 1,
        'name': 'France'
    }, {
        'id': 2,
        'name': 'Germany'
    }, {
        'id': 3,
        'name': 'Italy',
    }]
    countries = [{
            'id': 1,
            'name': 'France',
            'cities': ['Paris'],
            'places': [
                'effil tower',
                'new discover'
            ],
            'texts': ['a']
        },
        {
            'id': 2,
            'name': 'Germany',
            'cities': ['Hamburg'],
            'places': [],
            'texts': ['b']
        },
        {
            'id': 3,
            'name': 'Italy',
            'cities': ['Roma', 'Milan', 'Napoli'],
            'places': [
                'effil tower',
                'new discover'
            ],
            'texts': ['c']
        },
    ];

    ngOnInit() {
        this.onChange(1);
        this.serviceGetCountries();
        this.dropdown = new FormGroup({
            country: new FormControl(),
            city: new FormControl(),
            place: new FormControl(),
            text: new FormControl()

        });
    }
    getCountries() {
        return Observable.of(this.countriesValue);
    }

    serviceGetCountries() {
        this.getCountries().subscribe(res => {
            this.countrydrodown = res;
            console.log(this.countrydrodown);
        });
    }

    onChange(deviceValue) {
        console.log(deviceValue);
        this.getValues(deviceValue).subscribe(res => {
            console.log(res);
            this.cities = res.filter(x => x.id == deviceValue)[0].cities;
            this.places = this.countries.filter(x => x.id == deviceValue)[0].places;
            this.texts = this.countries.filter(x => x.id == deviceValue)[0].texts;
            console.log(Object.keys(this.places));
            console.log(this.cities);
        });
    }

    getValues(val) {
        return Observable.of(this.countries);


    }
}
<div [formGroup]="dropdown">
    <div class="col">
        <div class="row">
            <select formControlName="country" class="rounded-inputs20 select-select col-md-3" (change)="onChange($event.target.value)">
                <option selected *ngFor="let country of countrydrodown" [value]="country.id" selected="selected">{{country.name}}</option>
            </select>
        </div>
        <div *ngIf="cities?.length > 0" class="row">
            <div style=" padding-top: 0.5em; ">
                <select formControlName="city" id="sel1" class="">
                    <option *ngFor="let city of cities" [ngValue]="city" selected="selected">{{city}}</option>
                </select>
            </div>
        </div>
        <div *ngIf="places?.length > 0" class="row">
            <div style=" padding-top: 1em; ">
                <label *ngFor="let place of places">
                    <input formControlName="place" type="radio">{{place}}
                </label>
            </div>
        </div>
        <div *ngIf="texts?.length > 0" class="row">
            <div style=" padding-top: 1em; ">
                <label *ngFor="let text of texts">{{text}} :
                    <input formControlName="text" type="text">
                </label>
            </div>
        </div>
    </div>

</div>

Ответы [ 2 ]

2 голосов
/ 07 февраля 2020

Вот мое решение

В вашем шаблоне

<select formControlName="country" class="rounded-inputs20 select-select col-md-3" (change)="onChange($event.target.value)">
       <option value = "default" selected> Select Cities </option>
       <option *ngFor="let country of countrydrodown" [value]="country.id">{{country.name}}</option>
</select>

<select formControlName="city" id="sel1" class="">
       <option value = "default" selected> Select Cities </option>
       <option *ngFor="let city of cities" [ngValue]="city">{{city}}</option>
</select>

В вашем машинописном тексте добавьте:

public defaultSelect = "default";

Я надеюсь, что эта помощь

[EDIT]

Когда вы объявляете свойство defaultSelect = "default", значение внутри <option> будет установить на "default" и first option is selected. Select Cities в раскрывающемся списке всегда будет выбран и отображаться первым

0 голосов
/ 07 февраля 2020

Вам необходимо установить значение по умолчанию в вашей группе форм следующим образом:

this.dropdown = this.form.group({
    country: [1, Validators.required], //1 is the default value 
    ... (your others FormControl)
});

И в представлении просто выполните:

          <option
            *ngFor="let option of options"
            [value]="option.value"
            [innerHTML]="option.label"></option>
...