ngrxLet: A better version of the async pipe

Yesterday, we mentioned how the async pipe can be used with *ngIf or *ngFor in our templates to declare a local variable that allows us to have multiple expressions using the same data:

<div *ngIf="user$ | async as user">
   <p>First name: {{ user.firstName }}</p>
   <p>Last name: {{ user.lastName }}</p>
</div>Code language: HTML, XML (xml)

While the above code works perfectly well, it’s not always convenient to add an additional *ngIf or *ngFor in our templates. Another shortcoming of the async pipe is that it doesn’t let us know if the observable has an error or completes successfully.

This is where the ngrxLet directive can save the day, as it solves all of the above shortcomings with a straightforward syntax. Our previous example becomes:

<div *ngrxLet="user$ as user">
   <p>First name: {{ user.firstName }}</p>
   <p>Last name: {{ user.lastName }}</p>
</div>Code language: HTML, XML (xml)

And if we want to get any errors or the completion status of the observable, we can do so with more local variables exposed by ngrxLet:

<div *ngrxLet="user$ as user; error as e; complete as c">Code language: HTML, XML (xml)

You can find a complete working example here. ngrxLet can be installed as a dependency using npm (npm install @ngrx/component), and it’s important to note that it is not the entire ngrx state management library, just a tiny subset of it, so using that directive does not require using anything else from ngrx.

Here is a link to a slightly expanded version of that tutorial with more information if you want to dig deeper into it: ngrxLet – A better version of the async pipe.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.