在Angular 2模型驱动的表单中设置选择控件的选定选项

Mat*_*att 14 html angular

我已经在SO和其他地方研究过许多类似的现有答案,但是找不到解决方案.

我在Angular 2中使用模型驱动的方法来构建我的表单,这是一个添加和编辑表单.在编辑模式下,使用从服务检索的数据填充值:这方面都很好,因为简单的文本输入都正确绑定.

其中一个属性是"Country",这是一个如下对象:

    export class Country {id: number; name: string;}
Run Code Online (Sandbox Code Playgroud)

我想将它绑定到一个选择控件,该控件将包含可用的国家/地区列表,以及表单加载时填充的模型中的一个控件.我希望绑定的值是country对象,而不仅仅是id.

这是select控件的html:

    <select class="form-control" id="country" formControlName="country">
          <option value="default">--Select a country--</option>
          <option *ngFor="let c of countries" [value]="c">{{c.name}}      </option>
</select> 
Run Code Online (Sandbox Code Playgroud)

这是我尝试从组件类填充值的地方:

    (<FormControl>this.personForm.controls['country'])
 .setValue(this.person.country, { onlySelf: true });
Run Code Online (Sandbox Code Playgroud)

但是,当页面加载时没有选择的选项,即使控制台确认this.person.country存在并填充了正确的对象.

我可以使用id来处理它:在视图中更改为[value] ="c.id"并在类中附加.id,然后选择正确的选项.问题是select不再为country属性发出一个对象,只是id.我尝试将[value]更改为[ngValue]并获得相同的结果.我甚至将[ngModel] ="country"添加到select元素中,这也没有帮助.

我会感激任何帮助.

sil*_*sod 8

问题很可能this.person.countrycountry您的countries阵列中的问题不同.

如果我们想要使它们相同,我们可以显式订阅valueChangesselect控件或绑定[(ngModel)]person.country:

订阅更改

this.countryForm.controls['country'].valueChanges.subscribe(country => 
  this.person.country = country;
);

// initialize by finding the correct country object (this will overwrite the person's country object)
this.countryForm.controls['country'].setValue(countries.filter(c => c.id === person.country.id));
Run Code Online (Sandbox Code Playgroud)

模板

ngModel绑定

我们仍然必须使对象匹配(比较Angular 2使用的策略,这正是JS使用的)

this.person.country = this.countries.filter(c => c.id === this.person.country.id)[0];
Run Code Online (Sandbox Code Playgroud)

模板

<select class="form-control" id="country" formControlName="country" [(ngModel)]="person.country">
    <option value="default">--Select a country--</option>
    <option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)

ngModel Plunker: http ://plnkr.co/edit/UIS2V5rKh77n4JsjZtii?p =preview

订阅Plunker:http://plnkr.co/edit/yyZ6ol1NPD77nyuzwS2t?p = info