Angular 2 - 2 Way Binding with NgModel in NgFor
What you have done is not working because of two reasons.
- You have to use toDos[index] instead of item with ngModel (Read for more info)
- Each input has to have a unique name
Here's the working solution for your problem.
<div>
<div *ngFor="let item of toDos;let index = index;">
<input name=a{{index}} [(ngModel)]="toDos[index]" placeholder="item">
</div>
Below Should be binded to above input box
<div *ngFor="let item of toDos">
<label>{{item}}</label>
</div>
After digging around I need to use trackBy on ngFor. Updated plnkr and code below. Hope this helps others.
Working 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;
}
}