2
votes

I have 3 different arrays, each with a different length and each displayed visually using ngFor. They look something like this:

let list = [ {key:value},{key:value},{key:value},... ]

Through the course of my code I reorder and insert these arrays based on user input. I track the user input using the data-index property. Basically if you drag an element I grab the data-index attribute which tells me what element in the array I need to move and when you drop it I read the underlying elements data-index attribute to know where to insert it. The issue is after I make the modifications to the array the data-attribute never gets updated. This creates a problem for me because now my attribute no longer represents it's position in the array.

This is my template code:

  <div *ngFor="let item of list;let i = index;" [attr.data-index]="i">
    <div>....</div>
  </div>

This is my code to manipulate the list

this.list.splice(item.insertIndex, 0, item);

After this splice command I would expect the change to be pushed to ngFor and all my data-index attributes would be reset; meaning I always expect them to be 1,2,3,4,etc what I get is something like 1,4,2,17,3,1,4.

Is this expected behavior? If so is there a way to force a refresh or do I need to loop through each array and set the data-index attribute manually?

1

1 Answers

3
votes

As stated here Why is not updated model in ngFor after changed model?, just reasign your variable.

 this.list = [...this.list]

To force DOM refresh, refer to How to force a component's re-rendering in Angular 2?