Angular 2 – Pipes

Hi Friends,

Hope you are all well. This post is about how to implement pipes in your angular 2 apps. Pipes are basically used to format, manipulate data before it’s shown on the end user interface. You could use any of the pipes that come with angular 2 or write your own custom one as well.

Let’s begin.

The complete code of this tutorial is available here.

A screencast of this tutorial:

Clone the quick start app from angular site using the below command.

(cd into that directory and run npm install)

Now open up app.component.ts and add the below code.

Let’s break this down.

  1. | is the pipe symbol. randomval | number means we are applying the number pipe on the randomval variable.
  2. The pipes shown above all come with angular 2.
  3. 2.2-3 in the number pipe is an argument. It means 2 digits before the decimal point and minimum of 2 digits after the point and a maximum of 3 digits. (In our example the last two digits in decval 3 and 7 would be truncated.)

Now let’s see how to write a custom pipe.

Our custom pipe will take an argument which corresponds to the number of characters and it will also add hello to a string value. You could understand this better through code.

Create a new file hello.pipe.ts and add the below code.

@Pipe decorator is used here and the argument name specifies the name of the pipe. We take a string value as input and then concatenate hello along with its substring. The substring is split based on the input which we give.

Now open up app.component.ts and modify it to look like this.

Note that we have added pipes argument in our component and here we pass in the value 4 to our custom hellopipe. so the end result would be hello vict.

Similarly you could create your own custom pipes as well.

Hope this helped you guys. Thanks for reading. Peace.. :)


Liked it? Take a second to support admin on Patreon!