6
votes

I'm using *ngFor inside a page template (Ionic 2).

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

Somewhere inside the app, I update the children array when changes are detected (add, update, remove). I do this be assigning a new array to the property:

export class SharedParams {    
    private _children: Child[];

    constructor(children: Child[]){
        this._children = children;
    }

    get children(){
        return this._children;
    }

    set children(children: Child[]){        
        this._children = children;
    }
}

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.

I've also tried to manually modify the array instead of replacing it, using 'push' and 'splice'. But the behaviour stays the name. The DOM is never updated when an item is removed.

Any help would be greatly appreciated.

2
What kind of values does sharedParams.children contain? Normally replacing should work in any case. Can you provide a Plunker to reproduce?Günter Zöchbauer
sharedParams.children is an array of type Child (Child[]). This is a custom class containing some primitive properties (mostly strings).C. Sysmans
Never heard of such an issue. I suspect a problem with your code. A Plunker would be required to investigate.Günter Zöchbauer
What ionic version are you using? ( ionic --v ). I had a similar problem in beta.23 that was resolved in beta.25wdickerson
I have the same same problem. tried the same things as you C.Sysmans Addition or updating works, removal does notDylan Meeus

2 Answers

3
votes

You can use ChangeDetectorRef to check and update the list every 0.5 seconds or more...

For example:

constructor(private ref: ChangeDetectorRef) {
    console.log('Hello PhotoComponent Component');  
    setInterval(() => {
      this.ref.detectChanges();
    }, 500);  
  }
0
votes

In my case ChangeDetectorRef.detectChanges() did the trick. The problem seems to appear when you update the model from an Observable, for example the response of a Http.get().

Using NgZone.run() didn't help, I tried that before.