DOM not updating when removing item from ngFor array


#1

I’m using *ngFor inside a page template (Ionic 2 beta 7).

 <div class="child" *ngFor="let child of children">
         ...
 </div>

{{children.length}}

I update the children array when changes are detected (add, update, remove). I do this using ‘push’ and ‘splice’.

When an item is added or updated inside the array, the ngFor is triggered and the DOM is updated. However, when an item is removed, the array is changed, but the DOM does not remove the entry for that item.

The {{children.length}} also does not get updated when removing an item. It does when adding or updating.

I’ve also tried to replace the entire array with a new array. The same thing happens, adding and removing works fine, removing not.

Any help would be greatly appreciated.


#2

How do you remove this item?


#3

To remove an item from an array i’m using the splice method (since i’ve read that the slice method and angular 2 don’t work well together).

I also tried replacing the entire array, but no luck.

Even if I do:
this.children = [];
the DOM does not get cleared.


#4

It’s very strange. You debugged it? Are you sure that your remove method is called?


#5

Yes I am sure.
The array has 0 items, however the DOM still contains one or more items.

I’ve also seen similar behaviour with ion-slides.
I generate the slides using ngFor, based on an array.
When I update a slide, no problem. But when I try to remove a slide, nothing happens.


#6

For me it works. I use splice too… However I use object.

public remove(index: number): void {
  this.foo.bars.splice(index, 1);
}

You could use NgZone.


#7

In you example, what is the type of bars? Does it contain primitive types or complex objects.

How does NgZone work?


#8

array of complex objects

I recommend you read about ngZone. It’s not simply explain it and my English isn’t very good for this. But it was zonejs who decides when to update the DOM.
PS I never used it


#9

I have experimented some more, using NgZone and even by completely reconstructing the array from scratch, but the DOM is still not updating… weird behaviour -_-


#10

@csysmans In case that you updated your project from an earlier version of the framework I would suggest to check if you performed the update properly. If you missed something by the update, it might result in such a weird behavior. Check out the following post for more details: