Use "async as" to cleanup Angular templates

vanbalken

Van Balken

Posted on June 23, 2019

Use "async as" to cleanup Angular templates

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).

💖 💪 🙅 🚩
vanbalken
Van Balken

Posted on June 23, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related