简体   繁体   中英

Angular 2 components inside ngFor are not updated

I'm struggling for a few hours trying to update the view of my list of item.

I have a component called document-list . This component goes through each document passed to it and include a component called document-list-item .

<div *ngFor="let document of documents">
    <document-list-item [document]="document"></document-list-item>
</div>

When I update the list of document, the children views are not updated.

I tried those in the documents accessor of the document-list component :

public set documents(value: DocumentDetails[]) {
    this._documents = value;
    // used one by one
    this.changeDetector.detectChanges(); => doesn't work
    this.changeDetector.markForCheck(); => doesn't work
    this.appRef.tick(); => throw an error about recursivity
}

I also tried to manually update the list in the setters (well placed console.log showed me that it goes in) :

private _documents: DocumentDetails[] = [];
@Input()
public set documents(value: DocumentDetails[]) {
    this._documents = [];
    for (let i = 0; i < value.length; i++) {
        this._documents[i] = value[i];
    }
}
public get documents() {
    return this._documents;
}

The only thing that works was doing this in the accessor :

public set documents(value: DocumentDetails[]) {
    this.documents = [];
    setTimeout(() => {
        this._documents = value;
    }, 0);
}

It worked but it showed a blinking list each time the documents array were updated, which is not acceptable.

Any help is welcome

You have:

<document-list-item [document]="document"></document-list-item>

So you should have in your child class:

@Input()
document: any;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM