ExpressionChangedAfterItHasBeenCheckedError with ngClass

Modify you method like this:

    hideShowPanel(check: number) {
        setTimeout( ()=> {
            if (check == 1) {
                this.hidePanel2 = true;
                this.hidePanel1 = false;
            }
            else {
             this.hidePanel1 = false;
             this.hidePanel2 = true;
            }
       }, 0);
  }

Basically, ExpressionChangedAfterItHasBeenCheckedError occurs when the change detection has run and after that the expression value gets modified.


To add to Ritesh's answer, in this case you can do two things :

  • wrap the code that causes this message in a setTimeout() callback
  • Tell Angular to make another detection loops like this :

--

 constructor(private changeDetector: ChangeDetectorRef) {
 }

 hideShowPanel(check: number) {
 
    if (check == 1) {
        this.hidePanel2 = true;
        this.hidePanel1 = false;
    }
    else {
        this.hidePanel1 = false;
        this.hidePanel2 = true;
    }
    this.changeDetector.detectChanges();
}

I would also like to suggest an interesting article that explains what happens under the hood : Everything you need to know about ExpressionChangedAfterItHasBeenCheckedError