在 Angular 2 中,我如何使用 NgFor 在重复列表中获得与 NgModel 的双向绑定(bind)。以下是我的 plunkr 和代码,但出现错误。
@Component({
selector: 'my-app',
template: `
<div>
<div *ngFor="let item of toDos;let index = index;">
<input [(ngModel)]="item" placeholder="item">
</div>
Below Should be binded to above input box
<div *ngFor="let item of toDos">
<label>{{item}}</label>
</div>
</div>
`,
directives: [MdButton, MdInput]
})
export class AppComponent {
toDos: string[] =["Todo1","Todo2","Todo3"];
constructor() {}
ngOnInit() {
}
}
最佳答案
在深入研究之后,我需要在 ngFor 上使用 trackBy。更新了下面的 plnkr 和代码。
@Component({
selector: 'my-app',
template: `
<div>
<div *ngFor="let item of toDos;let index = index;trackBy:trackByIndex;">
<input [(ngModel)]="toDos[index]" placeholder="item">
</div>
Below Should be binded to above input box
<div *ngFor="let item of toDos">
<label>{{item}}</label>
</div>
</div>
`,
directives: [MdButton, MdInput]
})
export class AppComponent {
toDos: string[] =["Todo1","Todo2","Todo3"];
constructor() {}
ngOnInit() {
}
trackByIndex(index: number, obj: any): any {
return index;
}
}
关于Angular 2 - 在 NgFor 中使用 NgModel 的 2 种方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40314732/