简体   繁体   中英

Creating Angular4 'Loading' Screen: ExpressionChangedAfterItHasBeenCheckedError

I have created a custom loading screen where an Angular component (fullscreen DIV with SVG animation) is displayed above all other HTML. My issue is with calling the loading screen. At the moment, I have a boolean in a global service with an "_isLoading" variable. When set to true, the loading screen is displayed (and vice versa), as seen below:

<app-loading-screen *ngIf="dataService._isLoading"></app-loading-screen>
<div id="pageWrapper">
    <app-childcomponent></app-childcomponent>
</div>

By default, the '_isLoading' variable is set to 'true' to display the loading screen upon initial application load. The 'childcomponent' sets the '_isLoading' variable to 'false' once 'ngAfterViewInit' has been called, as the HTML from the child component has then loaded. This throws an 'ExpressionChangedAfterItHasBeenCheckedError'. I've read the In-Depth Blog Post on the error, and I understand that this problem is occurring due to the child component changing a variable that the digest cycle in the parent component just checked. What I don't know is how to get around this. I assume others have created Loading Screens before... What is the standard / norm for doing this?

ngAfterViewInit is exactly what gives you trouble. It is called after view has been updated with all values bound to it. So, at this moment you really should not change any data used in bindings. This also means that avoiding this error is pretty simple: all you need to do is just to wait for another change detection cycle. Simplest solution is to set timeout:

ngAfterViewInit() {
    setTimeout(() => {
        dataservice._isLoading = false;
    });
}

But actually, I would not implement setting of this flag from two different places. The reason being is that the component starting some operation assumes responsibility for updating that operation's status. Otherwise you will end up guessing "which component just killed this request?".

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