2

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?

user10012
  • 647
  • 1
  • 8
  • 23

1 Answers1

3

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?

  • Is this better/faster performance wise than looping through the array myself and updating the attribute manually? – user10012 Jun 19 '19 at 02:15
  • The problem is, "Angular doesn't recognise an array as having been changed if only it's contents have been changed. To let it know the array has changed just reassign the array object after removing an element and it should update on the DOM: " so you really need to reasign it by destructuring the array itself. https://stackoverflow.com/questions/47693951/why-is-not-updated-model-in-ngfor-after-changed-model – valhalla ross ferrer Jun 19 '19 at 02:21
  • So in this scenario I would need to clone both the from array and the to array correct? – user10012 Jun 19 '19 at 13:55
  • 1
    I don't know what you mean by cloning. My immediate workaround for your problem is `this.list.splice(item.insertIndex, 0, item); this.list = [...this.list];`. By doing this, angular will be able recognise that the array 'list' was updated. – valhalla ross ferrer Jun 20 '19 at 00:35