Async pipe in Angular from scratch

Tushar Upadhyay
Level Up Coding
Published in
2 min readOct 29, 2022

--

Basic pipe in angular

But what is a Pipe in Angular?

Pipes are used to transform input data. For example, we have an async pipe which takes a Promise or Observable and transforms it to a resolved or latest value in the case of an observable.

Built-in async pipe in Angular

Angular has a built-in pipe async we are going to make it from scratch but first understand how it works

As you can see we have a variable of type promise name which will resolve to ‘Angular 14’ after 3 seconds. Lets try to use it in our HTML file

But in output we can’t see Angular 14 after 3 seconds instead [Object Promise] is being shown in the output

So let's use async pipe to fix this

So by just adding | async we can see it showed ‘Angular 14’ after 3 seconds

Ok so now the interesting part let's try to code this pipe from scratch.

So how this works?

See, we have used impure pipe by setting pure=false, because we want to call the transform method when value(this.value) changes.

Initially, the value is null so it will return null first when the promise is in the pending state but after 3 seconds it will update the value to whatever data we have passed and this will cause transorm method to rerun and we will see ‘Angular 14’ in the output.

How to use this?

Add CustomAsync class in the declarations array in app.module.ts and use {{name | customAsync}}

Checkout its demo

https://stackblitz.com/edit/angular-ivy-oamp4e

--

--