Angular ngFor class binding ExpressionChangedAfterItHasBeenC



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

并在组件中返回 true 或 false 的简单 methis:

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

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

表达式已更改之后已检查错误:表达式在检查后已更改。以前的值:"假"。当前值:"真"。

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

ngOnInit() {
if (this.auth.isEmailVerified){
this.service.getPositions().
subscribe(positions => {
this.clientPositions=positions
});
}
else{
new NotVerifiedError(this.toast);
}
}

到目前为止,我一直在这个问题上。对于任何建议,将不胜感激。

您似乎会收到此错误,因为您正在传递由 angular 创建的DOM node,并且由于它的创建 angular 尝试调用方法来应用类。这会导致在开发模式下的双重更改检测期间产生不同的结果。

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

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

并像这样使用它:

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

最新更新