DEV Community

Mitch Lamers
Mitch Lamers

Posted on

Angular async pipe

The Angular async pipe is used to show values of an observable in the html of a component. The big advantage is that Angular will handle subscribing and unsubscribing to the observable and you will not have unused subscriptions.

Without async pipe

Imagine we are building a component to show some quotes

export class QuotesComponent implements OnInit {
  quotes: string[] = [];

  ngOnInit(): void {
    of([
      'Amor fati',
      'Memento mori',
      'Summum Bonum'
    ]).subscribe((values) => {
      this.quotes = values;
    });
  }
}
Enter fullscreen mode Exit fullscreen mode
<div *ngFor="let quote of quotes">
{{quote}}
</div>
Enter fullscreen mode Exit fullscreen mode

Now to handle the unsubscription we would also have to implement the onDestroy method, make the observable$ a class level variable and unsubscribe onDestroy of the component. Thats where the async pipe comes in.

With async pipe

export class QuotesComponent {
  quotes$: string[] = of([
      'Amor fati',
      'Memento mori',
      'Summum Bonum'
    ]);
}
Enter fullscreen mode Exit fullscreen mode

Here we use | async to handle the subscription

<div *ngFor="let quote of quotes$ | async">
{{quote}}
</div>
Enter fullscreen mode Exit fullscreen mode

Besides the advantage of not having to handle the subscriptions manually it also cleans up the code quite a bit

Top comments (0)