Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How properly bind an array with ngModel in angular 4?

Let's suppose I have an array [1,2,3]. I want to iterate all items and bind each to ngModel. When I run this code after changing the first element, the second one is getting the same value. What's the problem?

<div *ngFor="let x of array; let i = index;">
    <input type="number" [(ngModel)]="x[i]">
</div>
like image 640
Alexandrov Alexandr Avatar asked Oct 28 '17 15:10

Alexandrov Alexandr


People also ask

What does [( ngModel )] mean?

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.

What does the [( ngModel )] directive do in Angular?

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

Can ngModel have multiple values?

The solution is ng-bind-template, it can bind more than one {{}} expression, so it can show more than a single value that was declared in the Script function.


1 Answers

ngFor by default uses object identity to compare values, this breaks when primitive values (number, string, boolean) are used, because they change identity when modified). Using trackBy allows to configure ngFor to zse the index instead of identity:

<div *ngFor="let x of array; let i = index;trackBy:trackByIdx">
    <input type="number" [(ngModel)]="array[i]">
</div>
trackByIdx(index: number, obj: any): any {
  return index;
}
like image 137
Günter Zöchbauer Avatar answered Oct 27 '22 03:10

Günter Zöchbauer