简体   繁体   中英

Angular4 Change Detection ExpressionChangedAfterItHasBeenCheckedError

I'm trying to solve a problem, that didn't exist in AngularJS, due to the $digest -cycle checking everything.

I'm trying to create a component, that can initialize itself (async) and notify its surrounding container that the loading has been completed.

I have this pseudo-table:

<my-table>
    <ng-container *ngFor="let row in rows">
        <my-table-row
            [row]="row"
            [isLoading]="row.isLoading"
            (click)="onClickRow(row)"
        ></my-table-row>
        <my-detail-row *ngIf="row.isExpanded">
            <my-component
                [data]="row"
            ></my-component>
        ></my-detail-row>
    </ng-container>
</my-table>

In the surrounding component (that holds the rows ), I have the function onClickRow(row) which toggles row.isExpanded .

In the my-component component I want to set row.isLoading to true (notifying the "parent" row that it is loading) and then setting it to false after the API call is completed.

@Input() data: any;

ngOnInit() {
    this.task.isLoading = true; // PROBLEM

    setTimeout(() => { // simulate API call
        this.task.isLoading = false; // no problem
    }, 2000);
}

Now I get this error: Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'true'. Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'true'.

I guess this is because the change goes from my-component up the tree to ng-container but then not down to my-table-row ?

I have a workaround, in that I can use a second setTimeout() , around the first setting of this.task.isLoading , but this leads to some popin-effects and I would like to find a cleaner solution if possible.

Does anyone have a suggestion, how this can work?

I found a solution that I can live with.

You can inject the "parent" into your component (similar to require in AngularJS).

For this to work, you need to combine my-table-row and my-detail-row into something like my-item-row . This has the added benefit, that you can put the toggling-logic into the component and don't have to re-implement it on every use.

my-item-row.component.html :

<div
    class="item-row"
    (click)="onToggleDetail()"
>
    <div class="cell">...</div>

    <div *ngIf="isLoading" class="loading"></div>
</div>

<div
    *ngIf="isExpanded"
    [hidden]="!isInitialized"
    class="detail-row"
>
    ...
</div>

my-item-row.component.ts :

import { Component } from '@angular/core';
import { Input, ChangeDetectorRef } from '@angular/core';

@Component({...})
export class MyItemRowComponent {
    ...

    isInitialized: boolean = false;
    isLoading: boolean = false;
    isExpanded: boolean = false;

    constructor(private changeDetector: ChangeDetectorRef) { }

    onToggleDetail() : void {
        this.isExpanded = !this.isExpanded;
    }

    public startLoading() : void {
        this.isLoading = true;
        this.isInitialized = false;

        this.changeDetector.detectChanges(); // trigger re-evaluate
    }

    public stopLoading() : void {
        this.isLoading = false;
        this.isInitialized = true;

        this.changeDetector.detectChanges(): // trigger re-evaluate
    }
}

Now, you can inject this into my-component , like this:

my-component.component.ts :

import { Component } from '@angular/core';
import { Input, Host, Optional } from '@angular/core';

import { MyItemRowComponent } from '...';

@Component({...})
export class MyComponentComponent {
    ...

    // Optional, because there may be a case where we want to use it outside of a row
    constructor(@Optional() @Host() private parent: MyItemRowComponent) { }

    ngOnInit() { // or ngAfterViewInit, doesn't matter
        if (this.parent) {
            this.parent.startLoading();
        }

        setTimeout(() => { // simulate API call
            if (this.parent) {
                this.parent.stopLoading();
            }
        }, 2000);
    }
}

This is my current solution.

This lead to a different issue with the my-component being initiated, even when it wasn't expanded yet, see here:

Angular4 ng-content gets built when ngIf is false

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