Angular Pipes With Examples

Brief of Pipe 

  • In Angular 2, Pipes are mainly used to change the data display format.
  • By using the Pipe operator (|), we can apply the Pipe's features to any of the property in our Angular project.
  • In addition to that, we can also chain pipe and pass parameters to the Pipe.

Diagrammatic representation of Pipe classification
Angular

Below, we will look into the above concepts one by one with an example.

Brief of Built-In Pipes

  • Angular 2 provides many built-in Pipes which include uppercase, lowercase, decimal, date, percent, currency etc.
  • They are all available for use in any template in our Angular 2 project.

Syntax -  Property value | uppercase

Simple Built-In Pipe example

In this example, we will use uppercase pipes to change the employee name from lowercase letters to uppercase letters.

FileName 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6. </head>  
  7. <body>  
  8.     <table>  
  9.         <thead>  
  10.             <tr>  
  11.                 <th>Code</th>  
  12.                 <th>Name</th>  
  13.                 <th>Gender</th>  
  14.                 <th>Annual Salary</th>  
  15.                 <th>Date of Birth</th>  
  16.             </tr>  
  17.         </thead>  
  18.         <tbody>  
  19.             <tr *ngFor='let employee of employees'>  
  20.                 <td>{{employee.code}}</td>  
  21.   
  22.                 <td>{{employee.name|uppercase}}</td>  
  23.   
  24.                 <td>{{employee.gender}}</td>  
  25.                 <td>{{employee.annualSalary}}</td>  
  26.                 <td>{{employee.dateOfBirth}}</td>  
  27.             </tr>  
  28.             <tr *ngIf="!employees || employees.length==0">  
  29.                 <td colspan="5">  
  30.                     No employees to display  
  31.                 </td>  
  32.             </tr>  
  33.         </tbody>  
  34.     </table>  
  35. </body>  
  36. </html> 

Filename - app.component.ts

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.     templateUrl: 'app/app.component.html'  
  6. })  
  7. export class AppComponent {  
  8.   
  9.     employees: any[] = [  
  10.         {  
  11.             code: 'emp101', name: 'karthik', gender: 'Male',  
  12.             annualSalary: 5500, dateOfBirth: '25/6/1988'  
  13.         },  
  14.         {  
  15.             code: 'emp102', name: 'sachin', gender: 'Male',  
  16.             annualSalary: 5700.95, dateOfBirth: '9/6/1982'  
  17.         },  
  18.         {  
  19.             code: 'emp103', name: 'rahul', gender: 'Male',  
  20.             annualSalary: 5900, dateOfBirth: '12/8/1979'  
  21.         },  
  22.         {  
  23.             code: 'emp104', name: 'mary', gender: 'Female',  
  24.             annualSalary: 6500.826, dateOfBirth: '14/10/1980'  
  25.         },  
  26.     ];  
  27. }  

Output

Before applying the uppercase pipe:  just FYI

Angular
Same output, after applying the Uppercase pipe

Angular

Passing a parameter to Pipe

A Pipe can take any number of optional parameters to get the expected output.

Example 

In the below code, we will see the complete usage of date pipes 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.   
  6.     template: `<div>    
  7.     Parameterizing a pipe using DatePipe <br>   
  8.     <p>---------------------------------------</p>  
  9.          Medium:-{{DOB | date:"medium"}}<br/>  
  10.        Short:-{{DOB | date:"short"}}<br/>  
  11.       Specific Date Format:-{{DOB | date:"dd/MM/yyyy"}}<br/>       
  12.     Short Time format:-{{DOB | date:"shortTime"}}<br/>  
  13.     Medium Time:-{{DOB | date:"mediumTime"}}<br/>  
  14.     Medium Date format:- {{DOB | date:"mediumDate"}}<br/>  
  15.    Full Date Format:- {{DOB | date:"fullDate"}}<br/>  
  16.   
  17.       
  18.     </div>  `  
  19. })  
  20. export class AppComponent {  
  21.   
  22.      DOB = new Date(1947, 8, 15)   
  23. }  

Output

Angular

Passing multiple parameters to Pipe 

Let's use a currency example for this, which will be most frequently used in our projects.

Example

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.   
  6.     template: `<div>    
  7.     Passing Multiple Parameter to Pipe<br>   
  8.     <p>---------------------------------------</p>  
  9.         Annual Income :-{{salary  | currency:'USD':true:'1.3-3'}}<br/>  
  10.         
  11.     </div>  `  
  12.   
  13. })  
  14. export class AppComponent {  
  15.   
  16.     salary: number = 2602132  
  17.      

In the above code => currency:'USD': true:'1.3-3' is represent below,

  • The first parameter 'USD' is currency type which can be of INR, USD or any currency type in the world.
  • The Second parameter 'true' is a Boolean indicating whether to display currency symbol or not .By default it is false and, if we change it to true then the symbol will be displayed.
  • The Third parameter '1.3-3' is a range limit of type string, which has the following format

 Format syntax - {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} => {1}.{3}-{3}

  • minIntegerDigits is a minimum number of integer digits to use. The Defaults value is 1.
  • minFractionDigits is a minimum number of digits after fraction. The Defaults value is 0.
  • maxFractionDigits is a maximum number of digits after fraction. The Defaults value is 3.

Output

Angular

Chain Pipes Example 

By using the advantage of chaining, we can use two different pipes for the same property or column. Let us see how to use uppercase and date together in our example below.

Example 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.   
  6.     template: `<div>    
  7.     chaining a pipe <br>   
  8.     <p>---------------------------------------</p>  
  9.          
  10.    Full Date Format:- {{DOB | date:"fullDate"|uppercase}}<br/>  
  11.   
  12.       
  13.     </div>  `  
  14. })  
  15. export class AppComponent {  
  16.   
  17.     DOB = new Date(1947, 8, 15)  
  18. }  

Output

Angular
Custom Pipes

To create a pipe in Angular 2, you have to apply the @Pipe decorator to class, which we can import from the core Angular library.

The @Pipe decorator allows you to define the pipe name that you'll use within template expressions.

Syntax

  1. import { Pipe, PipeTransform } from '@angular/core';  
  2. @Pipe({ name: 'Pipename' })  
  3.   
  4. export class Pipeclass implements PipeTransform {  
  5.     transform(parameters): returntype { }  

Note

Transform() method will decide the input types, the number of arguments, and its types and output type of our custom pipe.

Custom Pipe Example 

Note
To easily understand, we will use same list example which we used in the above concept, and additionally provide the title (Mr. or Miss.) to the employees as per their gender value. 

Step 1

Create a file called employeeTitle.pipe.ts in the app folder. Add the code like below to that file.

File Name - employeeTitle.pipe.ts 

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

Step 2

Register this newly created class in your existing root module like below:

File Name-app.module.ts

Angular

Step 3

Add this line <td>{{employee.name | employeeTitle:employee.gender}}</td> to your existing HTML file called app.component.html. 

File name - app.component.html

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6. </head>  
  7. <body>  
  8.     <table>  
  9.         <thead>  
  10.             <tr>  
  11.                 <th>Code</th>  
  12.                 <th>Name</th>  
  13.                 <th>Gender</th>  
  14.                 <th>Annual Salary</th>  
  15.                 <th>Date of Birth</th>  
  16.             </tr>  
  17.         </thead>  
  18.         <tbody>  
  19.             <tr *ngFor='let employee of employees'>  
  20.                 <td>{{employee.code}}</td>  
  21.                 <td>{{employee.name | employeeTitle:employee.gender}}</td>  
  22.                 <td>{{employee.gender}}</td>  
  23.                 <td>{{employee.annualSalary | currency:'USD':true:'1.3-3'}}</td>  
  24.                 <td>{{employee.dateOfBirth}}</td>  
  25.             </tr>  
  26.             <tr *ngIf="!employees || employees.length==0">  
  27.                 <td colspan="5">  
  28.                     No employees to display  
  29.                 </td>  
  30.             </tr>  
  31.         </tbody>  
  32.     </table>  
  33. </body>  
  34. </html>  

That’s it.

Final Output

Angular
Conclusion 

Hope the above information will be very much helpful to implement pipes easily to our Angular project. Kindly let me know your thoughts or feedback. And, if you like to explore Angular concepts more, here are the links.


Similar Articles