Create Custom pipes in Angular

ng-hello.


A pipe is used to transform values in an Angular template. It takes in data as input and transforms it to a desired output. In this blog we will see what are all the built in pipes available and also we’ll explore how we can create custom pipes in Angular.

Built-in Pipes

Angular comes up with many built in pipes such as

  • DatePipe
  • CurrencyPipe
  • PercentPipe
  • async etc.

To explore more about Angular built-in pipes check out this link.

How to create Custom Pipes?

Creating a custom pipe is as much as easy as ordering a pizza. In this example, we are going to create a pipe called isEven which will take a number as an input and will check whether the number is even or odd and it will provide us the result appropriately.

STEP 1:

We are going to create an angular project called AngularApp using our angular CLI.

To do that, open command prompt as administrator and type ng new AngularApp.

STEP 2:

Once it is done, just open your web application in any one the code editors such as Visual Studio Code, Atom, Sublime etc.

In this example, I’m going to use Visual Studio Code. Just delete the contents which are available in app.component.html.

STEP 3:

Now we are going a create a file called isEvenPipe.ts. Right-click on the app folder and select New File and name it as isEvenPipe.ts. The file should contain the following code.

import { Pipe } from '@angular/core'
@Pipe({
name: 'isEven'
})

export class IsEvenPipe{
transform(value: number){
if(value%2 == 0)
return true;
return false;
}}

Explanation of the above code,

@Pipe – decorator which is used for creating the pipe
name – defines the name of pipe
transform() – The logic of this pipe should be present in this respective function

STEP 4:

Make sure you import your custom pipe in app.module.ts as mentioned below.

STEP 5:

And that’s it. You can use this custom pipe in html as,

{{any number | isEven}}

It will provide you the respective output once you run the angular application.

So if you run this application using ng serve then the output will be something like below.

Conclusion

So in this blog we explored about the built in pipes available in Angular and also we created an custom Angular pipe isEven. You can download the source code from below link.

https://github.com/SuhasParameshwara/IsEvenPipe

Happy Coding!

Cheers!

One thought on “Create Custom pipes in Angular

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: