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>
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 ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
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.
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;
}
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