1

I am looking forward to color some asynchronously received data in green or red, depending on its value.

To take care of race conditions, I used a Subject, which broadcasts an Object containing the data that I'm interested in.

I succeeded in doing what I wanted, but the resulting code is quite ugly :

<span [ngClass]="{greenClass: isPositive((mySubject | async)?.fieldData), redClass: !isPositive((mySubject | async)?.fieldData)}"> {{(mySubject | async)?.fieldData | number:'1.0-1' }} </span>

Is there a better way to tackle this ? I tried to put a ternary expression in ngClass but it didn't work. Moving code back to my controller is a no-go as it would result in the creation of ten variables straight away.

1 Answer 1

5

You can use an *ngFor to get a refernece to the subject value once it resolves to a value from the subscription like so:

<span *ngFor="let subject of [(mySubject | async)]"
      [ngClass]="{greenClass: isPositive(subject?.fieldData), redClass: !isPositive(subject?.fieldData)}">
    {{subject?.fieldData | number:'1.0-1' }}
</span>

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it enabled me to move the ngFor in the parent div and remove a lot of messy code.
Very nice little trick to use the async pipe on the view without conditionals!
This was an old answer so I am leaving it but there is now syntax for using an async pipe and an ngIf and assigning it to a variable which accomplishes the same as the above but is less hacky. angular.io/api/common/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.