[英]Angular ngFor class binding ExpressionChangedAfterItHasBeenCheckedError
I have an ngFor cycle which goes through an object I get from the server. 我有一个ngFor循环,它遍历了从服务器获取的对象。 Everything works well like this.
这样一切都很好。
<tr *ngFor="let item of clientPositions">
<td ">{{setStatus(item.exitPrice)}}</td>
</tr>
The component part just looks if there is a number coming in: 组件部分只是查看是否有数字输入:
setStatus(exitPrice) : any{
if (exitPrice>0)
return "closed";
return "open";
}
Pretty simple, if there was an exit price I assume the position was closed and I return closed as status. 很简单,如果有平仓价,我认为该头寸已平仓,而我又返回平仓状态。
Anyway, I want to color up the closed or open values so I add this. 无论如何,我想为关闭或打开的值着色,所以我添加了它。
<tr *ngFor="let item of clientPositions">
<td #status [class.openPos]="isPosOpen(status)"
{{setStatus(item.exitPrice)}}
</td>
</tr>
And a simple methis in the component to return true or false: 并在组件中返回一个简单的methis来返回true或false:
isPosOpen(status) {
let val = (status.innerText);
if (val==="open"){
return true;
}
return false;
}
Here I start having problems... First of all it is this error: 在这里我开始遇到问题...首先是这个错误:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。 Previous value: 'false'.
先前的值:“ false”。 Current value: 'true'.
当前值:“ true”。
I tried debuggin the isPosOpen(status) method in the console and it seems the cycle is spinned numerous times. 我尝试在控制台中调试isPosOpen(status)方法,似乎循环旋转了无数次。 Twice at least and I have no idea why angular does that.
至少两次,我不知道为什么用角度的。 Probably that is where the error occurs.
可能就是错误发生的地方。 The data is received OnInit like this:
像这样在OnInit上接收数据:
ngOnInit() {
if (this.auth.isEmailVerified){
this.service.getPositions().
subscribe(positions => {
this.clientPositions=positions
});
}
else{
new NotVerifiedError(this.toast);
}
}
So far I'm pretty stuck with this issue. 到目前为止,我对这个问题还很坚持。 Will be really gratefull for any suggestions.
对于任何建议,我们将不胜感激。
It seems like your getting this error because you're passing in a DOM node
which is created by angular and due to it's creation angular tries to invoke the method to apply the class. 似乎收到此错误的原因是,您传入的是由angular创建的
DOM node
,由于它是创建对象,所以angular尝试调用该方法以应用该类。 Which leads to a different outcome during double changeDetection in development mode. 在开发模式中,在两次更改检测期间会导致不同的结果。
You could just implement your isPosOpen
open method like this: 您可以像这样实现
isPosOpen
打开方法:
isPosOpen(item: any) {
return item && item.exitPrice === 0;
}
And use it like this: 并像这样使用它:
[class.openPos]="isPosOpen(item)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.