1

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.

enter image description here

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.

5
  • Can you provide reproduction in plunker? Commented Oct 4, 2017 at 10:18
  • It is actually complicated because i loop through data, But everything is here Commented Oct 4, 2017 at 10:22
  • The main problem here is that your checkPositive method is executed after ngStyle binding has been applied and inside checkPositive method you have side effect. angular.io/guide/template-syntax#no-visible-side-effects Commented Oct 4, 2017 at 10:24
  • Sure, that's exactly what the problem is, however I can't seem to find a solution Commented Oct 4, 2017 at 10:26
  • [ngStyle]="{ color: contract.transactionAmount ? 'blue' : 'red' } and remove this.color inside checkPositive method Commented Oct 4, 2017 at 10:27

1 Answer 1

2

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'"> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.