Angular 2 * ng incorrect for updating handles

I have the following problem: I use this * ngFor loop:

<app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>

if the "subsectors" of the array look 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. These "sector applications" components are added inside the "sector applications" component. Parent gets their subsectors from their parent through "@Input" in my "application".

Here's what 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 the problem starts here: When I update subsections 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);

* ngFor does not create new components and only destroys a few. I can not see the template. This seems to be a random decision if it destroys or creates new components.

sofar: trackBy. trackBy, id, . :

<app-sector *ngFor="let subsector of sector.subsectors; trackBy:identify;" [sector]="subsector"></app-sector>

identify(index,item){
    return item.id;
}

, , , , . Parent :

ngOnChanges(changes) {
    if(this.sector['subsectors']) {
        setTimeout(() => {
            console.log('spliced subsectores for reinitialization');
            this.sector['subsectors'] = this.sector['subsectors'].slice();
        }, 1000);
    }
}

, ! , , , :)

.

+4
2

. changeDetection: ChangeDetectionStrategy.OnPush @Component({}). Angular2 , . - .

0

, , , translcusion


?

:

<app-root>
    <app-sector *ngIf="playlist" [sector]="playlist">
        <app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>
    </app-sector>
</app-root>

<app-sector> <app-sector>, , ng-content somwhere app-sector.

*ngFor ng-content.

.

, , ( , . , ().

, 3 , . , .

0

Source: https://habr.com/ru/post/1678388/


All Articles