在NgFor中使用NgModel进行角2-2方式绑定 [英] Angular 2 - 2 Way Binding with NgModel in NgFor
本文介绍了在NgFor中使用NgModel进行角2-2方式绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Angular 2中,我如何使用NgFor在重复列表中与NgModel进行2种方式绑定.以下是我的代码和代码,但出现错误.
In Angular 2 how would I get 2 way binding with NgModel within a repeating list using NgFor. Below is my plunkr and code but I get an error.
@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和代码.希望这对其他人有帮助.
After digging around I need to use trackBy on ngFor. Updated plnkr and code below. Hope this helps others.
@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;
}
}
这篇关于在NgFor中使用NgModel进行角2-2方式绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文