Home > other >  Angular ngFor duplicates first value when I add to the front of the list
Angular ngFor duplicates first value when I add to the front of the list

Time:12-15

I have a simple list I iterate through with ngFor. The ngFor is inside a form element so I have to use the name attribute with ngModel to display values. My problem comes when I add to the front of the list, the new element gets added but also changes the previous first elements value (only the value in the DOM) to the newly added value.

Here's the link to an example of what's going on.

Anyone know why the old first element gets changed in the DOM?

CodePudding user response:

I know how avoid: using trackby

<div *ngFor="let testUnit of testList; let i = index;trackBy:trackBy">
...
</div>

And in .ts

  trackBy(index,obj)
  {
    return index
  }

But the reason is relation about ngModel and the need of give name. But really I don't know the mechanism :(

Update There're another way that is that the "name" don't relation with the "i"

If we imagine that our array is like

  testList = [
    { index:0,value: 'placeholder 1' },
    { index:1,value: 'placeholder 2' },
    { index:2,value: 'placeholder 3' },
  ];

And the "add" like

add() {
    this.testList.unshift({ index:this.testList.length,
                            value: 'new value' });
  }

We can use

<div *ngFor="let testUnit of testList; let i = index;">
  <input
    
    [name]="'name' testUnit.index"
    [(ngModel)]="testUnit.value"
  />
</div>
  • Related