我有一个选择列表,我想将其初始化为从服务器返回的保存值。但无论我尝试什么,我都无法让它使用选定的值。
我正在使用 Angular 2.2.0和Reactive Forms。
这是选择列表的值列表。
private categoryList: ICategory[] = [
new Category({ id: 1, name: 'Cat 1' }),
new Category({ id: 2, name: 'Cat 2' }),
new Category({ id: 3, name: 'cat 3' })
];
保存的值为:
{ id: 1, name: 'Cat 1' }
使用 FormBuilder 我创建了表单
this.itemForm = this.fb.group({
name: [null, Validators.required],
description: [null, Validators.required],
weight: [null, Validators.required],
dimensions: [null, Validators.required],
category: [null, Validators.required]
});
然后我用保存的数据初始化它
(<FormGroup>this.itemForm)
.setValue({
name: item.name,
description: item.description,
weight: item.weight,
dimensions: item.dimensions,
category: item.category
}, { onlySelf: true });
模板看起来像这样
<select name="category" [formControl]="itemForm.controls['category']">
<option [selected]="itemForm.controls['category'].value == null" value="">-- Select --</option>
<option *ngFor="let cat of categories" [ngValue]="cat">
{{cat.name}}
</option>
</select>
{{itemForm.controls['category'].value | json }}
预期结果 select 中选择了第一项的名称,并与模板下显示的 JSON 中的文本匹配
实际行为 JSON 显示了这一点:
{ "id": 1, "name": "Cat 1" }
但是选择中没有选择任何内容
如果选择了 --Select--,则 JSON 会正确更新为“”。
如果选择了另一只猫,JSON 也会正确更新。
我在做什么错,如何初始化选择?
编辑我也试过这个:
<option *ngFor="let cat of categories" [selected]="itemForm.controls['category'].value.id == cat.id" [ngValue]="cat">