Several Ways to Use Async Pipes in Angular

Kürşat Coşkun
Frontend Weekly
Published in
3 min readJun 20, 2020

In this article, I will explain the “Async Pipes” in Angular. Besides, we will examine the use of async pipes and their different uses on many examples here. So, actually when I started writing Angular, I used to write codes with subscribes in many components. As you learn about the reactive programming logic in Angular and see how beautiful and fast it works, this structure, which is subscribe to the stream on the template side, has become much more important. Also I can say Async Pipes better than the Subscribe blocks.

Subscribe() Usage

Simple Async Pipe Usage

In a simple example seen above, its use is quite understandable. However, let’s think there are many observables and we need to use async pipe on the template side. What do you think we should do?

There are 3 different observable and async pipes in different places in the template. The complexity of the template will increase as the number of Observable subscribers increases here.

There is a much more effective way here. Using ng-container and * ngIf Directive.

There is an additional way. This is using CombineLatest, the RxJS operator.

Obviously, if we have many getter methods on the component side, we can use the combineLatest operator to send the data returned by these getter methods to the template side in one place.

Subscribe() vs Async Pipes

While working with observables, we should use pipes because it is obviously the cleanest way. When we subscribe to a Stream on the Component side, we need to be unsubscribe to the objects we subscribe to, in Angular’s life cycle method, ngOnDestroy(). Angular handles subscriptions async pipes for us automatically. We do not need any ngOnDestroy method implementation or unsubscribe of observable.

Also there is a problem with using subscibe blocks.Subscribing to the observable manually in the ngOnInit() doesn’t work with OnPush change detection strategy out of the box.

Although the way to use subscribe() is more readable and understandable on the template side, it is more advantageous to use async pipe in terms of performance.

Conclusion

Angular offers us pretty good ways for Observable and data streams. Here we have to think, which situations should be which way to choose. If we are extensively creating a project with State Management structures such as NgRx, NGXS, we will have quite a lot of async pipes in the template here. It will be better in terms of code quality and performance in terms of code quality and performance by controlling and presenting them to the template from one place with ng-container and * ngIf directives.

--

--