ExpressionChangedAfterItHasBeenCheckedError Explained

前端 未结 26 1521
慢半拍i
慢半拍i 2020-11-22 14:46

Please explain to me why I keep getting this error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

Obviously,

相关标签:
26条回答
  • 2020-11-22 15:45

    There were interesting answers but I didn't seem to find one to match my needs, the closest being from @chittrang-mishra which refers only to one specific function and not several toggles as in my app.

    I did not want to use [hidden] to take advantage of *ngIf not even being a part of the DOM so I found the following solution which may not be the best for all as it suppresses the error instead of correcting it, but in my case where I know the final result is correct, it seems ok for my app.

    What I did was implement AfterViewChecked, add constructor(private changeDetector : ChangeDetectorRef ) {} and then

    ngAfterViewChecked(){
      this.changeDetector.detectChanges();
    }
    

    I hope this helps other as many others have helped me.

    0 讨论(0)
  • 2020-11-22 15:46

    In my case, I had this problem in my spec file, while running my tests.

    I had to change ngIf to [hidden]

    <app-loading *ngIf="isLoading"></app-loading>
    

    to

    <app-loading [hidden]="!isLoading"></app-loading>
    
    0 讨论(0)
  • 2020-11-22 15:46

    The solution...services and rxjs...event emitters and property binding both use rxjs..you are better of implementing it your self, more control, easier to debug. Remember that event emitters are using rxjs. Simply, create a service and within an observable, have each component subscribe to tha observer and either pass new value or cosume value as needed

    0 讨论(0)
  • 2020-11-22 15:47

    I had a similar issue. Looking at the lifecycle hooks documentation, I changed ngAfterViewInit to ngAfterContentInit and it worked.

    0 讨论(0)
  • 2020-11-22 15:47

    I hope this helps someone coming here: We make service calls in ngOnInit in the following manner and use a variable displayMain to control the Mounting of the elements to the DOM.

    component.ts

      displayMain: boolean;
      ngOnInit() {
        this.displayMain = false;
        // Service Calls go here
        // Service Call 1
        // Service Call 2
        // ...
        this.displayMain = true;
      }
    

    and component.html

    <div *ngIf="displayMain"> <!-- This is the Root Element -->
     <!-- All the HTML Goes here -->
    </div>
    
    0 讨论(0)
  • 2020-11-22 15:48

    To anyone struggling with this. Here's a way to debug properly this error : https://blog.angular-university.io/angular-debugging/

    In my case, indeed I got rid of this error using this [hidden] hack instead of *ngIf...

    But the link I provided enabled me to find THE GUILTY *ngIf :)

    Enjoy.

    0 讨论(0)
提交回复
热议问题