Angular ngFor class 绑定 ExpressionChangedAfterItHasBeenCheckedError
Angular ngFor class binding ExpressionChangedAfterItHasBeenCheckedError
我有一个 ngFor 循环,它遍历我从服务器获取的对象。这样一切都很好。
<tr *ngFor="let item of clientPositions">
<td ">{{setStatus(item.exitPrice)}}</td>
</tr>
组成部分就是看有没有数字进来:
setStatus(exitPrice) : any{
if (exitPrice>0)
return "closed";
return "open";
}
很简单,如果有退出价格,我假设头寸已平仓,我 return 已平仓。
无论如何,我想给封闭值或开放值涂上颜色,所以我添加了这个。
<tr *ngFor="let item of clientPositions">
<td #status [class.openPos]="isPosOpen(status)"
{{setStatus(item.exitPrice)}}
</td>
</tr>
组件中的一个简单方法 return true or false:
isPosOpen(status) {
let val = (status.innerText);
if (val==="open"){
return true;
}
return false;
}
这里我开始遇到问题...首先是这个错误:
ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'false'。当前值:'true'.
我尝试在控制台中调试 isPosOpen(status) 方法,似乎循环旋转了很多次。至少两次,我不知道为什么 angular 这样做。可能这就是发生错误的地方。 OnInit 接收数据是这样的:
ngOnInit() {
if (this.auth.isEmailVerified){
this.service.getPositions().
subscribe(positions => {
this.clientPositions=positions
});
}
else{
new NotVerifiedError(this.toast);
}
}
到目前为止,我一直被这个问题困扰。非常感谢任何建议。
您收到此错误似乎是因为您传入了由 angular 创建的 DOM node
并且由于它的创建 angular 尝试调用要应用的方法class。这导致在开发模式下的双重更改检测期间出现不同的结果。
您可以像这样实现 isPosOpen
打开方法:
isPosOpen(item: any) {
return item && item.exitPrice === 0;
}
并像这样使用它:
[class.openPos]="isPosOpen(item)"
我有一个 ngFor 循环,它遍历我从服务器获取的对象。这样一切都很好。
<tr *ngFor="let item of clientPositions">
<td ">{{setStatus(item.exitPrice)}}</td>
</tr>
组成部分就是看有没有数字进来:
setStatus(exitPrice) : any{
if (exitPrice>0)
return "closed";
return "open";
}
很简单,如果有退出价格,我假设头寸已平仓,我 return 已平仓。
无论如何,我想给封闭值或开放值涂上颜色,所以我添加了这个。
<tr *ngFor="let item of clientPositions">
<td #status [class.openPos]="isPosOpen(status)"
{{setStatus(item.exitPrice)}}
</td>
</tr>
组件中的一个简单方法 return true or false:
isPosOpen(status) {
let val = (status.innerText);
if (val==="open"){
return true;
}
return false;
}
这里我开始遇到问题...首先是这个错误:
ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'false'。当前值:'true'.
我尝试在控制台中调试 isPosOpen(status) 方法,似乎循环旋转了很多次。至少两次,我不知道为什么 angular 这样做。可能这就是发生错误的地方。 OnInit 接收数据是这样的:
ngOnInit() {
if (this.auth.isEmailVerified){
this.service.getPositions().
subscribe(positions => {
this.clientPositions=positions
});
}
else{
new NotVerifiedError(this.toast);
}
}
到目前为止,我一直被这个问题困扰。非常感谢任何建议。
您收到此错误似乎是因为您传入了由 angular 创建的 DOM node
并且由于它的创建 angular 尝试调用要应用的方法class。这导致在开发模式下的双重更改检测期间出现不同的结果。
您可以像这样实现 isPosOpen
打开方法:
isPosOpen(item: any) {
return item && item.exitPrice === 0;
}
并像这样使用它:
[class.openPos]="isPosOpen(item)"