12

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>

1 Answers1

36

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;
}
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 5
    wow fantastic this took me ages. I had an input field, in a component, that lost focus on every key press. This fixed it. Simple array of strings as you state works fine if using array of objects and referencing keys in object. – Gurnard Jun 02 '20 at 09:21
  • 1
    This fixed it for me too! thanks! – manfall19 Jan 06 '22 at 07:58