ngIf-检查后表达式已更改 [英] ngIf - Expression has changed after it was checked

查看:349
本文介绍了ngIf-检查后表达式已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的场景,但是无法正常工作!

I have a simple scenario, but just can't get it working!

在我看来,我会在一个高度有限的框中显示一些文本.

In my view I display some text in a box with limited height.

正在从服务器获取文本,因此输入文本时视图会更新.

The text is being fetched from the server, so the view updates when the text comes in.

现在,我有一个扩展"按钮,其中包含一个ngIf,如果框中的文本溢出,则显示该按钮.

Now I have an 'expand' button that has a ngIf that should show the button if the text in the box is overflowing.

问题在于,由于文本在获取时发生更改,因此在Angular的更改检测完成后,展开"按钮的条件变为true.

The problem is that because the text changes when it is fetched, the 'expand' button's condition turns to true after Angular's change detection has finished...

因此我收到此错误:检查表达式后,表达式已更改.先前的值:"false".当前值:"true".

显然该按钮不显示...

Obviously the button does not show...

请参见柱塞 (请查看控制台以查看错误...)

see this Plunker (check the console to see the error...)

有什么主意要怎么做吗?

Any idea how to make this work?

推荐答案

发生此错误是因为您在dev mode中:

this error occur because you in dev mode:

dev mode中,每次执行常规更改检测后,更改检测都会增加一圈,以检查模型是否已更改.

In dev mode change detection adds an additional turn after every regular change detection run to check if the model has changed.

所以,要强制更改检测运行到下一个刻度,我们可以执行以下操作:

so, to force change detection run the next tick, we could do something like this:

export class App implements AfterViewChecked {

  show = false; // add one more property

  constructor(private cdRef : ChangeDetectorRef) { // add ChangeDetectorRef
    //...
  }
  //...
  ngAfterViewChecked() {
    let show = this.isShowExpand();
    if (show != this.show) { // check if it change, tell CD update view
      this.show = show;
      this.cdRef.detectChanges();
    }
  }

  isShowExpand()
  {
    //...
  }
}

实时演示: https://plnkr.co/edit/UDMNhnGt3Slg8g5yeSNO?p=preview

这篇关于ngIf-检查后表达式已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆