简体   繁体   中英

Error: ExpressionChangedAfterItHasBeenCheckedError - Angular

I have an array of data I loop wit *ngFor . I just want to check if a value is under or above 0, so I've made a checkPositive function. Here's the HTML code :

<div class="col-xs-4" [ngStyle]="{'color':color}">
    <span>{{checkPositive(contract.transactionAmount) | number: '1.2-2'}} {{contract.contractCurrency}}</span>
</div>

And the ts file

checkPositive(amount){
    if(amount > 0){
      this.color="blue";
      return amount;
    }
    else{
      this.color="red";
      return amount;
    }
  }

The result I get is that the first number has no color set.

在此处输入图片说明

and the console returns

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'blue'.

I understand what the problem is, I just don't know how to solve it.

The problem is that you are using same component property for all the entry in your list.

Just try to do this

<div class="col-xs-4" [ngStyle]="{'color': contract.transactionAmount > 0 ? 'blue':'red'}">
    <span>{{ contract.transactionAmount | number: '1.2-2'}} {{contract.contractCurrency}}</span>
</div>

or

<div class="col-xs-4" [style.color]="contract.transactionAmount > 0 ? 'blue':'red'">

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