I have the following Problem: I am using this *ngFor loop:
<app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>
if the Array "subsectors" looks like this:
var subsectors = [
{text: 'test', title: 'test', id: 'abc'},
{text: 'test123', title: 'test123', id: 'def'},
{text: 'test321', title: 'test321', id: 'ghi'}
]
It adds 3 "app-sector"-Components as expected. Those "app-sector"-Components are being added inside an "app-sector"-Component. The parent gets his subsectors from his parent via "@Input" in my "app-component".
This is how the HTML-Structure looks like:
<app-root>
<app-sector *ngIf="playlist" [sector]="playlist">
<app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>
</app-sector>
</app-root>
Now here is where the Problem starts: When I update the subsectors like this:
//Add new subsectors
this.subsectors.push({text: 'Blah', title: 'Blah', id: '123'});
this.subsectors.push({text: 'Blah123', title: 'Blah123', id: '456'});
this.subsectors.push({text: 'Blah321', title: 'Blah321', id: '789'});
//Remove old subsectors
this.subsectors.splice(2, 1);
this.subsectors.splice(1, 1);
this.subsectors.splice(0, 1);
The *ngFor doesn't create new Components and only destroys a few. I can't really see a pattern. It seems to decide randomly if it destroys or creates new Components.
Here is what i've tried sofar: Use trackBy. I added a trackBy filter which returned the "id" property but it didn't change anything. Here is how:
<app-sector *ngFor="let subsector of sector.subsectors; trackBy:identify;" [sector]="subsector"></app-sector>
identify(index,item){
return item.id;
}
then i tried some Tricks i've seen while researching this issue, like using slice instead of splice. Or in the Parent i tried to do this:
ngOnChanges(changes) {
if(this.sector['subsectors']) {
setTimeout(() => {
console.log('spliced subsectores for reinitialization');
this.sector['subsectors'] = this.sector['subsectors'].slice();
}, 1000);
}
}
I hope you can help me! Please ask me in the comments if you need any further information to help me :)
kind regards.