首页 > 解决方案 > 如何在 Angular 中使用 ngFor 设置选择下拉菜单中的第一项

问题描述

我在下面有这个下拉列表,其中包含所有国家/地区,但不显示第一个值(“美国”)。我怎样才能让第一个项目成为选定的项目?

如果 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;

标签: htmltwitter-bootstraptypescriptangular7

解决方案


从 countryList 为您想要的 formControl 分配初始值。

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


推荐阅读