DEV Community

loading...

Use "async as" to cleanup Angular templates

vanbalken profile image Van Balken Updated on ・1 min read

The result from an AsyncPipe can be stored in a local variable:

<span *ngIf="person$ | async as person">
    Hello {{ person.name }}
</span>

The local variable can be used in the scope of the ngIf. This can reduce the need of additional AsyncPipes and ? operators.

The important part is the as with which you can store the conditional result of the ngIf in a local variable (See: Angular Docs).

I found out about this by reading: Handling Observables with NgIf and the Async Pipe @ Ultimates Courses. I recommend reading it for more information.

The Angular Style Guide doesn't mention how to name your Observables. But in the documentation of the RxJS library they say: It can be convenient to name Observables with a trailing "$" (Angular Docs).

Discussion (3)

pic
Editor guide
Collapse
constjs profile image
Piotr Lewandowski • Edited

I'd like to see directive for this in Angular core ;)

*ngIf has drawback to check falseness of value.
For example when observed values are numbers, when value comes by and is 0, it will never be shown.

<span *ngIf="counter$ | async as counter">
    Hello {{ counter }}
</span>

This is something to know to avoid surprises. ;)

Collapse
wassimchegham profile image
Wassim Chegham

Thanks for writing about the async pipe 👍

Collapse
sanidz profile image
sanidz

In case you don't need ngif just ommit it and go for Elvis operator :)

Hello {{ (person$ | async)?.name }}