ExpressionChangedAfterItHasBeenCheckedError with ngClass
Asked Answered
S

2

10

I have two anchor tags

 <ul class="switchNav">
          <li [ngClass]="!hidePanel2 ? 'active' : ''">
            <a href="javascript:void(0)" (click) ="hideShowPanel(1)">panel 1</a>
          </li>
          <li [ngClass]="!hidePanel1? 'active' : ''">
            <a href="javascript:void(0)" (click) ="hideShowPanel(2)">panel 2</a>
          </li>
        </ul>

.ts

hidePanel2: boolean  = true;
 hidePanel1: boolean  = false;

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

  }

When I click on anchor tag it throws an error

ExpressionChangedAfterItHasBeenCheckedError

It was working,but due to update any module by a team member it stopped working,

I have googled a lot but could not get it working

Please help

Thanks

Sturdivant answered 24/9, 2018 at 7:25 Comment(0)
Z
8

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

Zolner answered 24/9, 2018 at 7:37 Comment(0)
D
3

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.

Damn answered 24/9, 2018 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.