使用ngClass时出现ExpressionChangedAfterItHasBeenCheckedError错误

10

我有两个锚点标签

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

  }

当我点击锚点时,会抛出错误

ExpressionChangedAfterItHasBeenCheckedError

之前它是可以用的,但由于团队成员更新了某个模块,它停止工作了。

我已经谷歌过很多次,但无法使它工作。

请帮忙。

谢谢。

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错误,你需要知道的一切


3

请将您的方法修改为以下内容:

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

基本上,当变化检测运行并且之后表达式值被修改时,就会出现ExpressionChangedAfterItHasBeenCheckedError错误。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接