DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How to build async pipe in Angular from scratch
Tushar Upadhyay
Tushar Upadhyay

Posted on

How to build async pipe in Angular from scratch

Basic async pipe in angular
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

App component

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

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

HTML file
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:-

Custom Pipe
So how this works?

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)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another β€œCoder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.