user2024080
user2024080

Reputation: 5091

How to handle `ngIf` with async pipe values?

I am trying to implement the ngIf with using async pipe. but not works. any one help me here?

here is my html:

<div class="response-container">
    xx {{response | async | json }}
    <div class="failed-error" *ngIf="(response.responseFail | async )">
        {{response.message}}
    </div>
    <div class="success-msg" *ngIf="(response.responseSucc | async) === 'true' ">
        {{response.message}}
    </div>
</div>

in the above xx {{response | async | json }} it prints as:

xx { "responseFail": false, "responseSucc": true, "message": "success" }

But why this is not works with *ngIf condition?

Upvotes: 3

Views: 2071

Answers (3)

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

Besides the previous answers, you shouldn't use the async pipe on the same observable several times.

Better do this: (naming observabkes with $ is best practice)

<div *ngIf="response$ | async as response" class="response-container">
    xx {{response | json }}
    <div class="failed-error" *ngIf="response.responseFail">
        {{response.message}}
    </div>
    <div class="success-msg" *ngIf="response.responseSucc">
        {{response.message}}
    </div>
</div>

And since those div's only differ in class you should consider using ng-class

Upvotes: 1

Crocsx
Crocsx

Reputation: 7589

you have to access the object after the async pipe =>

*ngIf="(response | async )?.responseFail"

ex =>

https://stackblitz.com/edit/angular-tvmqzm

edit : ethan got here first.

Upvotes: 3

Ethan Vu
Ethan Vu

Reputation: 2987

The response is a data source while response.responseFail is not one. Try this:

*ngIf="(response | async )?.responseFail"

*ngIf="(response | async)?.responseSucc  === 'true' "

Upvotes: 5

Related Questions