简体   繁体   中英

How to set the first item in a select drop down using ngFor in Angular

I have this drop down below and it has all the countries in it, but doesn't display the first value ('United States'). How can I get the first item to be the selected one?

Is it possible to have a conditional statement that sets 'selected' if index = 0? I know two bindings aren't possible, but I'm looking at other alternatives.

 <div class="form-group"> <select id="country" class="form-control" formControlName="countryList"> <option *ngFor="let country of countryList;" value={{country}}> {{country}} </option> </select> </div> 

and below is what I see in the page. No item is initially selected. It's blank until I select something!

在此处输入图片说明

Update - I'm trying this below, but it doesn't seem to work either.

[value]="country" 
[selected]="country == 'United States' ? true : null"

CountryList looks like this

 export class Countries { countryList: string[] = ['United States', 'Afghanistan', 'Albania']; CountryList() { return this.countryList; } } // to initialize it, in my component I do this countryList: string[] = new Countries().countryList; 

Assign initial value to the formControl which you want from the countryList.

ex:- controlModel.controls['countryList'].setValue('United States');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM