Angular 2 - 2 Way Binding with NgModel in NgFor
AngularTypescriptAngular Problem Overview
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() {
}
}
Angular Solutions
Solution 1 - Angular
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;
}
}
Solution 2 - Angular
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>
Solution 3 - Angular
Try this
@Component({
selector: 'my-app',
template: `
<div>
<div *ngFor="let item of toDos;let index = index;">
<input [(ngModel)]="item.text" placeholder="item.text">
</div>
Below Should be binded to above input box
<div *ngFor="let item of toDos">
<label>{{item.text}}</label>
</div>
</div>
`,
directives: [MdButton, MdInput]
})
export class AppComponent {
toDos: any[] =[{text:"Todo1"},{text:"Todo2"},{text:"Todo3"}];
constructor() {}
ngOnInit() {
}
}
Solution 4 - Angular
You have to add a name attribute to the ngModel with name + index to make it unique.
<mat-form-field
#fileNameRef
appearance="fill"
color="primary"
floatLabel="auto"
>
<input
matInput
#fileNameCtrl="ngModel"
name="originalName{{ index }}"
[(ngModel)]="file.originalName"
type="text"
autocomplete="off"
autocapitalize="off"
readonly
/>
</mat-form-field>