繁体   English   中英

计算得到错误的值:ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

[英]calcuate value getting the error : ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

我需要帮助来解决问题,我需要显示由 forgroup 数据计算的值,因为它改变了我猜错误显示,但我尝试了很多方法来解决它(如 ngAfterViewChecked 等),但没有任何帮助..有什么建议么?

ts

 calcPercentageToUnproot() {
    //:number
    let trees: FOTreeInfoModel[] = this.fg.get("treesGridArray").value;
    trees.forEach(element => {
      if(element.actionReasonID.code==eActionReason.Unproot)
      {
        this.unprootSum=this.unprootSum+element.quantityOfTrees;
        this.allcalcTrees=this.allcalcTrees+element.quantityOfTrees;
      }
      else{
        this.allcalcTrees=this.allcalcTrees+element.quantityOfTrees;
      }
    });

    if (this.allcalcTrees > 0) {
      this.treesPercentageToUnproot = Math.floor(
        (this.unprootSum * 100) / this.allcalcTrees
      );
    } else if (this.allcalcTrees == 0) {
      this.treesPercentageToUnproot =null;
    }

  }

html

<h4 *ngIf="treesPercentageToUnproot" class="p-col-12 mr-1rem">{{treesPercentageToUnproot}}%</h4>

当您处于开发模式时 angular 检测到两次更改,因此当它发现差异时,它会抛出此错误,在生产模式下此错误不存在。 要解决它,您需要让 angular 知道您所做的更改,因此您需要使用ChangeDetectionRef - 您将其注入构造函数中 -

constructor(private cdr: ChangeDetectionRef) {}

然后在更改treesPercentageToUnproot的值后需要检测更改:

if (this.allcalcTrees > 0) {
  this.treesPercentageToUnproot = Math.floor(
    (this.unprootSum * 100) / this.allcalcTrees
  );
} else if (this.allcalcTrees == 0) {
  this.treesPercentageToUnproot =null;
}
this.cdr.detectChanges();

这将使 angular 知道您所做的更改。

祝你好运:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM