The Techies' pub

Angular 2 – Pipes

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.

| is the pipe symbol. randomval | number means we are applying the number pipe on the randomval variable.

The pipes shown above all come with angular 2.

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.

1

2

3

4

5

6

7

8

9

10

11

import{Pipe,PipeTransform}from'angular2/core';

@Pipe({name:'hellopipe'})

exportclassHelloPipeimplementsPipeTransform{

transform(value:string,args:string[]){

if(value){

return'hello '+value.substring(0,parseInt(args[0]));

}

}

}

@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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import{Component}from'angular2/core';

import{HelloPipe}from'./hello.pipe';

@Component({

selector:'my-app',

template:`<h1>{{mydate|date:'MMM yyyy'}}</h1>

<h1>{{randomval|number}}</h1>

<h1>{{decval|number:'2.2-3'}}</h1>

<h1>{{curr|currency:'INR':true}}</h1>

<h1>{{name|hellopipe:'4'}}</h1>`,

pipes:[HelloPipe]

})

exportclassAppComponent{

mydate=newDate();

randomval=123456;

decval=2.45637;

curr=452;

name='victor';

}

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.