Angular 2 ngControl和空选择

时间:2016-06-02 11:34:29

标签: angular

在我的应用程序中,我选择标签创建与ngFor循环,它工作正常,直到我添加ngControl。现在,当页面加载时,没有选择默认选项。为什么第一个选项不用作默认值?

<select  class="form-control icon-caret" name="country" ngControl="country_id">
     <option  *ngFor="let item of countries"  [value]="item.id">
           {{item.name}}
     </option>
</select>

1 个答案:

答案 0 :(得分:0)

我想这是因为在表单模型中创建了一个控件,其默认值为""

我希望你将select绑定到模型上(你如何获得所选的值?)。如果设置bound属性的初始值(例如在构造函数中),则将选择该项:

<select [(ngModel)]="selectedCountry" class="form-control icon-caret" name="country" ngControl="country_id">
     <option  *ngFor="let item of countries"  [value]="item.id">
           {{item.name}}
     </option>
</select>
class MyComponent {
  selectedCountry;
  countries = [{id: 'USA'}, {id: 'GB'} ];
  constructor() {
    this.selectedCountry = this.countries[0];
  }
}