But what is a Pipe in Angular?
Pipes are used to transform input data into something. For example we have async pipe which takes a Promise or Observable and transforms it to a resolved or latest value in case of a 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 lets 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 lets try to code this pipe from scratch:-
See, we have used impure pipe by setting pure=false, because we want to call transform method when value(this.value) changes.
Intially the value is null so it will return null first when the promise is in 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
Top comments (0)