Create Custom Pipe in Angular 8

Krishan Kumar February 12, 2020

Create Custom Pipe in Angular 8

What is Pipe?

It is used to transform data into a user readable format. It helps in custom formatting of data in an Angular template. The essence of a Pipe is that it is typically used for transforming data for user friendly UI.

Example –

In most of the cases, A layman prefers to see a date in simple format like “April 10, 1973” rather than the raw string format “Fri Apr 12 1980 00:00:00 GMT-0700 (Pacific Daylight Time)”.

In-Built pipes in Angular

Angular provides us many in-built pipes :

1) DatePipe

2) CurrencyPipe

3) LowerCasePipe

4) UpperCasePipe

5) TitleCasePipe

 

One can easily transform or style data as illustrated below:

 

Pipe with parameters is illustrated below:

We can pass parameters in the pipe to format data in the desired form.

 

Chaining Pipe is illustrated below:

Pipes can be chained together to serve various purposes. In this case birthday is chained to date pipe as well as uppercase pipe.

Custom pipes:

We can create our own custom pipes to transform the data as per our requirements.

Steps to create a custom Pipe:

1) Create a pipe with the command “ng generate pipe trim” where trim is the name of the pipe.

2) Your pipe file will be created and its declaration will be added automatically to the app.module.ts file as shown below:

 

3) Write a variable in file app.component.ts which will be rendered in HTML file:

 

4) Create logic to remove whitespace between the words in the trim.pipe.ts file :

 

5) Now use this pipe to format your data in app.component.html file :

 

In this way, we can create a custom pipe to format the data. In this case, our input string is “Hello Angular”. And its output is illustrated below :

Thank you for taking the time to read my article.
Share it with your friends if you find it useful. All questions and suggestions are welcome in the comment section.
Cheers!

If you have any queries or doubts about this topic, please feel free to contact us. We are here to help you!

Lets’s Talk

About your ideas and concept