繁体   English   中英

如何在Angular中使用ngFor在选择下拉菜单中设置第一项

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

我在下面有一个下拉菜单,其中包含所有国家/地区,但未显示第一个值(“美国”)。 我怎样才能使第一个项目成为所选项目?

如果index = 0,是否可以有条件语句设置“ selected”? 我知道两个绑定是不可能的,但是我正在寻找其他替代方法。

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

下面是我在页面中看到的。 最初没有选择任何项目。 在我选择某物之前,它是空白的!

在此处输入图片说明

更新-我在下面尝试此操作,但它似乎也不起作用。

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

CountryList看起来像这样

 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; 

将初始值分配给想要从countryList获得的formControl。

例如:-controlModel.controls ['countryList']。setValue('United States');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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