Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - 2 Way Binding with NgModel in NgFor

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() {   } } 
like image 313
Ka Tech Avatar asked Oct 29 '16 00:10

Ka Tech


People also ask

Is ngModel two-way binding?

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.

What does [( ngModel )] do?

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.

Is angular 2 support two-way data binding only?

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.

Is ngModel property binding?

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.


1 Answers

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;   } } 
like image 81
Ka Tech Avatar answered Sep 20 '22 12:09

Ka Tech