Angular async pipe
Mitch Lamers
Posted on October 8, 2022
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;
});
}
}
<div *ngFor="let quote of quotes">
{{quote}}
</div>
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'
]);
}
Here we use | async
to handle the subscription
<div *ngFor="let quote of quotes$ | async">
{{quote}}
</div>
Besides the advantage of not having to handle the subscriptions manually it also cleans up the code quite a bit
Posted on October 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.