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).
Top comments (3)
I'd like to see directive for this in Angular core ;)
*ngIfhas 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.This is something to know to avoid surprises. ;)
Thanks for writing about the async pipe 👍
In case you don't need ngif just ommit it and go for Elvis operator :)
Hello {{ (person$ | async)?.name }}