首页 文章

Angular ngFor类绑定ExpressionChangedAfterItHasBeenCheckedError

提问于
浏览
0

我有一个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>

并且组件中的一个简单的methis返回true或false:

isPosOpen(status) {

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

return false;
}

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

ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后发生了变化 . 上一个值:'false' . 当前值:'true' .

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

ngOnInit() {

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

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

到目前为止,我仍然坚持这个问题 . 对任何建议都会非常感激 .

1 回答

  • 0

    看起来你得到这个错误是因为你传入了一个由angular创建的 DOM node ,并且由于它的创建角度试图调用该方法来应用该类 . 在开发模式下的双重更改检测期间会导致不同的结果 .

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

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

    并像这样使用它:

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

相关问题