Angular 2+ Pipes

Pipes provide a very easy way to manipulate data on the client side. It can be used to change the displayed numbers (for currency for example), manipulate strings (uppercase, lowercase, etc) and more. You can also create your custom pipe and use it anywhere easily


Simple example:

In the component code declare:

In the template add:

here we use the date built in pipe with a parameter to determine how exactly we want it to be displayed


More examples of built in pipes:

Lets first we create a new type – Book:

now add a books array to your component code:

Add a table to the template:


Using some built in pipes:

Change the book name to uppercase:

Change the book name to titlecase (only first letter for each word is uppercase):

Display the price with currency

Display the price with currency symbol and digit limit

see more in Angular reference


Creating a custom pipe:

first use the Angular CLI

It will create a single file to implement the pipe

now implement the simple transform function:

Change the value parameter type to any type you want and also the return value

For example here we get a string and return a new string with some ‘*’ signs

Now you can apply the new pipe

In the template add:

thats it – to reuse it anywhere you only need to add the source file to the project and add the type name to the declaration section of the module decorator


Currency example:

Implementation – Add $ and 2 fixed digit ( 120 ==>  ‘$ 120.00’ )

Use it


Adding a parameter

let the user decide how many fixed digit

using the pipe:


Creating pipe for a custom type:

# ng g p booksfil

Now we want to manipulate data array – here we filter it but we can also sort , group etc.

The pipe works on a Book array and also returns Book array, It gets a filter string as a parameter and filter the array to the books with the substring found in their name

declare in the component code:

Add a textbox for the filter:

Add the pipe to the ngFor statement


Adding support for case insensitive


You can implement any pipe you want, just declare the input and output types and implement the transform function





Leave a Reply

Your email address will not be published.