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

4

2 回答 2

8

要添加到 Ritesh 的答案,在这种情况下,您可以做两件事:

  • 将导致此消息的代码包装在setTimeout()回调中
  • 告诉 Angular 进行另一个检测循环,如下所示:

--

 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();
}

我还想推荐一篇有趣的文章来解释幕后发生的事情:关于 ExpressionChangedAfterItHasBeenCheckedError 你需要知道的一切

于 2018-09-24T07:37:38.410 回答
3

像这样修改你的方法:

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

基本上,ExpressionChangedAfterItHasBeenCheckedError 在更改检测运行时发生,之后表达式值被修改。

于 2018-09-24T07:30:20.513 回答