Bring reactivity to your Angular templates with the LetDirective - Part 1

Part one of the step-by-step tutorial on how to implement your own structural directive for binding an Observable to the Angular view.


TL;DR

  • Angular's built-in AsyncPipe serves as a convenient way to bind Observable values to the view.

  • Even though it solves most of the use-cases, using it comes with some downsides:

1. It can be painful to deal with falsy values.

2. It does not work in the zone-less environment.

3. It only notifies about the next-ed values, thus ignoring error and complete notifications.

4. For complex use-cases it requires a lot of boilerplate code, especially when combining with

*ngIf.

  • We can solve the above issues by using the structural LetDirective.

  • The LetDirective offers all the basic AsyncPipe features (like emitting switching context for different Observable notifications and subscribing/unsubscribing automatically on component's initialization/destruction) and adds a convenient API on top of it.

  • The LetDirective allows us to switch view based on the source Observable's notifications (complete and error).


Introduction

Angular has a pretty convenient way to bind an Observable to the view context. The popular AsyncPipe serves exactly that purpose:

<app-hero-card [hero]="hero$ | async"></app-hero-card>
<>
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks. (source: official docs)

In its core, the AsyncPipe does its job well:

  • It applies values emitted from the source Observable to the view.

  • It stops emitting when the source Observable completes.

  • It stops emitting and displays an