Pipes In Angular 5

In this article we will be discussing Pipes in Angular 5. Pipes are the operators which is used to format data in Angular. This comes from the symbol (|) used to do this operation. Pipes are there in Angular from Angular2 onwards. But it has evolved over the period of time. There are many inbuilt pipes available in Angular 5 and it gives an easy template to create your own pipe using @angular/cli.

Introduction

In this article, we will be discussing Pipes in Angular 5. Pipes are the operators that are used to format the data in Angular. This comes from the symbol (|) used to do this operation. Pipes are there in Angular from Angular v2 onwards. But it has evolved over the period of time. There are many inbuilt pipes available in Angular 5 and it gives an easy template to create your own pipe using @angular/cli.

Newbies to Angular 5 should check Hello world with Angular5 before moving to this topic.

All the built-in pipes are available in @angular/common npm package under CommonModule.

Inbuilt Pipes in Angular5

Before jumping into the custom pipes in Angular, let's first discuss the inbuilt pipes of Angular.

String pipes

UpperCase Converts the string type data to upper case in the UI.
lowercase Converts the string type data to lower case in the UI.
titlecase Converts the string type data in which the first alphabet of each word is made capital and the rest will be in the small case.
Slice : <starting index> It works on string fields or Array. It slices the input from the index till the end of the string or array length.
Slice : <starting index>:<end index> It works on string fields or array. It slices the input from the starting index to the end index. (excluding the end index)

Code for the same:

HTML part 

  1. <h2>string pipes</h2>  
  2. <h3>{{authorPosition | uppercase}} : {{authorName}}</h3>  
  3. <h3>Article Name : {{articleName | titlecase}}</h3>  
  4. <br>  
  5. <h4>slice demo</h4>  
  6. <h4>{{articleName | slice :5 }}</h4>  
  7. <h4>{{articleName | slice :5:8 }}</h4>  

Typescript part

  1. this.authorPosition = "blogger";  
  2. this.authorName = "Biswabid";  
  3. this.articleName = "pipes in angular";  

output 

output

Date pipes

There are many date type pipes available in Angular. Following are some of the important ones.

shortDate It converts the date to a short date.
longDate It provides the long date for the date. Provides full month name then day and year.
fullDate It provides the full date for the date. i.e day, month date, year

Please find the list of date pipes here.

Code for the same,

HTML part 

  1. <h2>Date pipes</h2>  
  2. <h3>{{currentDate}}</h3>  
  3. <h3>{{currentDate | date:'shortDate'}}</h3>  
  4. <h3>{{currentDate | date:'longDate'}}</h3>  
  5. <h3>{{currentDate | date:'fullDate'}}</h3>  

TypeScript part

this.currentDate = new Date();

output

output

Other pipes

Let’s talk about some more handy pipes available in Angular5. 

Currency Formats a number as currency.
Currency : <currency type of country> Formats a number as a currency of the specific country. It takes country currency type as a parameter.
DeprecatedCurrencyPipe Formats a number as currency to a specific decimal format.

Code for the same, 

  1. <td>{{credit.salary | currency}}</td>  
  2. <td>{{credit.salary | currency : 'INR'}}</td>  
  3. <td>{{credit.salary | currency : 'INR' : true : '8.2'}}</td>  

Output

output

Explanation

As you can observe the 1st salary column in USD.

As I pass the currency type (INR) as a parameter for the 2nd column, the output type is formatted to INR.

In the 3rd scenario, I wanted the data in a specific way i.e. 8 characters before decimal and 2 characters after the decimal. In the output 2, 0s are appended before the number.

Custom pipes in Angular 5

There are times in development you will need to create a pipe of your own to accommodate your specific requirement. For that Angular provides custom Pipe option. It’s really very easy to generate a custom Pipe using @Angular/Cli.

Following is the command you can use in the terminal(in Visual studio code) to generate your custom Pipe.

ng generate pipe [name]

output

Above is the screenshot for the same command execution.

Once I executed the command, it created a spec.ts and pipe.ts files in my Pipes folder.

It updated the app.module.ts file automatically to add the related dependencies.

Following is the generated code in title.pipe.ts file.

  1. import { Pipe, PipeTransform } from '@angular/core';  
  2.   
  3. @Pipe({  
  4.   name: 'title'  
  5. })  
  6. export class TitlePipe implements PipeTransform {  
  7.   
  8.   transform(value: any, args?: any): any {  
  9.     return null;  
  10.   }  
  11.   
  12. }  

And below is the updated code in app.module.ts file.

  1. import { TitlePipe } from './Pipes/title.pipe';  

Angular will automatically append Pipe after the name you have used to generate.

Here in the title.pipe.ts implements the PipeTransform class so it’s having an auto-generated function transform in it.

Let’s modify it get the title of a person. If the person is male then it would append Mr. else, Miss. To the name of a person.

Title.pipe.ts

  1. import { Pipe, PipeTransform } from '@angular/core';  
  2.   
  3. @Pipe({  
  4.   name: 'title'  
  5. })  
  6. export class TitlePipe implements PipeTransform {  
  7.   
  8.   transform(value: any, gender : string): any {  
  9.     if (gender == 'male'){  
  10.       return "Mr." + value;  
  11.     }  
  12.     else{  
  13.       return "Miss." + value;  
  14.     }  
  15.   }  
  16.   
  17. }  

I have modified the transform function. It takes the gender of the person as an argument. It checks if the gender is male, then returns the name appending Mr. or Miss.

Component.html

  1. <table border= "1px solid black">  
  2.     <thead>  
  3.         <th>Name</th>  
  4.         <th>Gender</th>  
  5.         <th>Salary</th>  
  6.         <th>Date of joining</th>  
  7.     </thead>  
  8.     <tbody>  
  9.         <tr *ngFor='let credit of credits; let i = index'>  
  10.             <td>{{credit.name | title : credit.gender}}</td>  
  11.             <td>{{credit.gender}}</td>  
  12.             <td>{{credit.salary | currency}}</td>  
  13.             <td>{{credit.DOJ | date:'shortDate'}}</td>  
  14.         </tr>  
  15.     </tbody>  
  16. </table>  

Here, I am creating a table and using custom Title pipe on name column. I am passing credit.gender as argument to the transform function.

Apart from that, I am using currency pipe on salary and date pipe on DOJ column in the table.

Component.ts

  1. interface Icredit{  
  2.   name : string;  
  3.   gender : string;  
  4.   salary : number;  
  5.   DOJ : Date;  
  6. }  
  7. export class AboutComponent implements OnInit {  
  8.   credits : Icredit[];  
  9.   authorPosition : string;  
  10.   authorName : string;  
  11.   articleName : string;  
  12.   currentDate : Date;  
  13.   constructor() {   
  14.     this.credits = [];  
  15.     this.authorPosition = "blogger";  
  16.     this.authorName = "Biswabid";  
  17.     this.articleName = "pipes in angular";  
  18.       
  19.     this.currentDate = new Date();  
  20.     this.credits[0] = <Icredit>{name:"John",gender:"male",salary:1000000, DOJ : new Date("02/01/2015")};  
  21.     this.credits[1] = <Icredit>{name:"Julli",gender:"female",salary:10000, DOJ : new Date("02/31/2016")};  
  22.     this.credits[2] = <Icredit>{name:"Jack",gender:"male",salary:90000, DOJ : new Date("05/08/2016")};  
  23.     this.credits[3] = <Icredit>{name:"Jasmin",gender:"female",salary:80000, DOJ : new Date("04/09/2018")};  
  24.     this.credits[4] = <Icredit>{name:"Joe",gender:"male",salary:95000, DOJ : new Date("07/12/2015")};  
  25.   }  
  26.   
  27.   ngOnInit() {  
  28.   }  
  29. }  

I have created an interface named ICredit. I am creating an array and populating 5 items in it in the constructor().

Output

output

References

Please let me know your feedback/comments. Happy Coding!!