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.
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() { } }
ngModel DirectiveThe [(ngModel)] syntax is the recommended way of two-way data binding. The ngModel directive with [] syntax is used for one-way data binding. [ngModel] binds a value to a property to UI control.
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.
The two-way data binding in Angular enables data to flow from the component to the view and the other way round. It is used to display information to the end-user and allows them to make changes to the underlying data using the UI.
NgModel is a directive that creates the FormControl instance from a domain model and binds it to a form control element. It uses two kinds of binding: Property binding.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With