【问题标题】:Angular ngFor class binding ExpressionChangedAfterItHasBeenCheckedErrorAngular ngFor 类绑定 ExpressionChangedAfterItHasBeenCheckedError
【发布时间】:2018-02-03 15:17:13
【问题描述】:

我有一个 ngFor 循环,它遍历从服务器获取的对象。一切都像这样运行良好。

<tr *ngFor="let item of clientPositions"> 
    <td ">{{setStatus(item.exitPrice)}}</td>     
</tr>

组件部分只是看是否有数字进来:

setStatus(exitPrice) : any{

    if (exitPrice>0)
      return "closed";

      return "open";
}

很简单,如果有退出价格,我假设该头寸已平仓,并返回已平仓状态。

无论如何,我想为关闭或打开的值着色,所以我添加了这个。

<tr *ngFor="let item of clientPositions"> 

      <td #status [class.openPos]="isPosOpen(status)"
              {{setStatus(item.exitPrice)}}
      </td>         
</tr>

以及一个简单的方法在组件中返回真假:

isPosOpen(status) {

let val = (status.innerText);
if (val==="open"){
  return true;
}

return false;
}

在这里我开始遇到问题...首先是这个错误:

ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:“假”。当前值:'true'。

我尝试在控制台中调试 isPosOpen(status) 方法,似乎循环旋转了很多次。至少两次,我不知道为什么 Angular 会这样做。可能这就是错误发生的地方。 OnInit 接收数据如下:

ngOnInit() {

if (this.auth.isEmailVerified){
  this.service.getPositions().
  subscribe(positions => {
    this.clientPositions=positions

  });
}
else{
  new NotVerifiedError(this.toast);
}
}

到目前为止,我还很纠结这个问题。非常感谢任何建议。

【问题讨论】:

  • 不使用 isPosOpen(status),为什么不使用 setStatus(item.exitPrice) === 'open'?
  • 我建议阅读这个答案,你会得到一些关于这个问题的提示stackoverflow.com/questions/45467881/…
  • 我认为错误是因为您将模板(td)引用到该模板属性([class.openPos])的方法,这也发生在我上周
  • 此错误将进入生产模式

标签: angular html-table ngfor


【解决方案1】:

您似乎收到此错误,因为您传入了一个由 angular 创建的DOM node,并且由于它的创建,angular 尝试调用该方法来应用该类。这会导致开发模式下的双重 changeDetection 产生不同的结果。

你可以像这样实现你的isPosOpen open 方法:

isPosOpen(item: any) {
  return item && item.exitPrice === 0;
}

并像这样使用它:

[class.openPos]="isPosOpen(item)"

【讨论】:

  • 谢谢,我忘了你可以在方法参数中传递一个项目,我试图像这样传递它 {{itme.exitPrice}} 并且遇到错误,但我一读到你的答案很明显,正是 DOM 更改检测算法在干扰这种情况,所以我刚刚通过了 [class.openPos]="isPosOpen(item)",现在我可以用它做任何我想做的事情。谢谢。
猜你喜欢
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 2017-11-25
  • 2018-01-20
相关资源
最近更新 更多