Angular 2 Pipe : Create a custom Angular 2 Pipe

In this article, we will talk about Angular 2 Pipe. In Angular 2, we have lots of Pipes but in your project development cycle, you will withstand a situation where you would like to create your own pipe. Here, we will understand how to create a new  Angular 2 Pipe and how to use them our templates.






Setting up our Application

Let’s use Angular CLI to setup our application. If you don’t have Angular CLI installed on your machine run the below command to install it globally.
npm install -g angular-cli
After Angular CLI installation,to create a new Angular project Run below command. This command will create all the necessary files, download all the required external dependencies and do all of the setup work for us.

ng new AppName


Angular 2 Pipe

Ready with Angular CLI ?

Now to run the below command to create an Angular 2 Pipe.

ng g -g pipe nameOfThePipe

In this application, we will create 2 Pipes listed below,

  1. AgeMultiplier : To manipulate the age of users.
  2. emailConcat : To concat Email: string with the email address of the user.

So let’s create these Pipes,run the below command,

  1. ng g -g pipe ageMultiplier : To create AgeMultiplier Pipe.
  2. ng g -g pipe emailConcat : To create emailConcat Pipe.

Cool, now you can use your created pipe in your application anywhere and in any template.

You know why ? because when you use Angular CLI for your Angular2 projects, it automatically adds the declaration in @NgModule decorator. Check out app.modules.ts file.



The application

Before using our created Pipes let’s first take a look at our application, where we have a list of users.





Using Angular 2 Pipe

Now let’s use our created pipes one by one.

Using emailConcat Pipe:

Open email-concat.pipe.ts file and replace the code by below code.

In the below code,

  1. We are returning the email address by concating the Email: to the left.
  2. The transform method takes the arguments as a string in this case and returns a string.



Now in template file,
We have to use PIPE( | ) operator to use the pipe as shown in below code.


Using ageMultiplier pipe:

Here, we will understand how to pass a parameter to the Pipe. Now open the age-multiplier.pipe.ts file and replace code by below code.
In the below code,

The transform method we expect two parameters, the first parameter will be the default value and second parameter will be a multiplier which we will pass from the template.

age-multiplier.pipe.ts :


In the template file,
we will pass a parameter to the pipe, by using a colon ( : ) symbol a shown below.


Now run the app everything should work fine.

For now, that’s it.  In this article, we understood below points,

  1. How to create Angular 2 Pipe.
  2. How to use them Angular 2 Pipe.
  3. how to pass parameters to it.

If you like this article, consider sharing with your friends.