简体   繁体   中英

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

I need help to solve the problem, I need to show value, that calcuate by the forgroup data, because it changes I guess the error shows, but I tried many ways to solve it(like ngAfterViewChecked etc..) and nothing helped.. any suggestions?

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>

when you're in development mode angular detects changes twice, so when it finds differences, it throws this error, in production mode this error does not exist. to solve it you need to let angular know about the change you made so you need to use ChangeDetectionRef - you inject it in the constructor -

constructor(private cdr: ChangeDetectionRef) {}

and then after you change the value of the treesPercentageToUnproot need to detect the changes:

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

this will let angular know about the changes you made.

good luck:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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