我的打字稿课上有以下对象:
export class XComponent {
fields: [{ }];
constructor() {
this.fields = [
{
id: 'Id1',
name: 'Field 1',
value: 'lorem'
},
{
id: 'Id2',
name: 'Field 2',
value: 'ipsum'
},
{
id: 'Id3',
name: 'Field 3',
value: 'dolor'
},];
}
}
当我尝试在输入元素中动态绑定值时,它将绑定最后一个值 dollt 。
<div *ngFor="let field of fields; index as i">
<label>{{ field.name }}</label> <!-- This one is rendered correctly. -->
<input type="text" [(ngModel)]="fields[i].value" />
</div>
Label: Field 1
Input: dolor
Label: Field 2
Input: dolor
Label: Field 3
Input: dolor
答案 0 :(得分:3)
您不再需要传递索引。您正在考虑使用* ngFor
数组对象<div *ngFor="let field of fields;">
<label>{{ field.name }}</label> <!-- This one is rendered correctly. -->
<input type="text" [(ngModel)]="field.value" />
</div>
这是一个正在运行的演示https://stackblitz.com/edit/angular-fre6m5
答案 1 :(得分:1)