Introduction To Angular Pipes

This article explains how to use Angular built-in pipes like uppercase, lowercase, titlecase, date, percent, number, currency, slice, and JSON pipe, and how to create your customized pipes as well.

If you would like to read my previous article on Angular, please visit the below links.

The following topics have been covered in this article.

  1. Pipe Syntax
  2. Passing parameter for a Pipe
  3. Using multiple pipes (chaining pipes)
  4. Case Conversion Pipes

    1. UpperCasePipe
    2. LowerCasePipe
    3. TitleCasePipe

  5. DatePipe
  6. PercentPipe
  7. DecimalPipe
  8. CurrencyPipe
  9. SlicePipe
  10. JsonPipe
  11. Creating Custom pipes

    1. Alternate case pipe
    2. Opinion pipe

Angular Pipes can be used to transform data to desired output. Angular provides a lot of inbuilt pipes, apart from that we can create our custom pipes as well very quickly.

If you are coming from an AngularJS background, then you must remember that in AngularJS we use filters which can be used for Formatting, Sorting, and Filtering. However, in Angular, we use Pipe only for formatting. Following is a tabular representation for the same.

 AngularJS FilterAngular Pipe
FormattingYESYES
SortingYESNO
FilteringYESNO

So, you can say that in Angular, Pipe has only one responsibility, i.e. formatting of the data.

Pipe Syntax

The syntax for using pipe in Angular is straightforward. Just use data or expression and pipe name separated with a pipe ‘|’ symbol.

 data | pipeName

Passing parameter for a pipe

We can pass any number of parameters to the pipe using a colon (:)

 data | pipeName: parameter 1 : parameter 2 : parameter 3 …. : parameter n

Using multiple pipes (chaining pipes)

We can use multiple pipes with the same data at the same. This also referred to as chaining pipes

data | pipe 1 | pipe 2 | pipe 3 | ……… pipe n

OR

data | pipe 1 : parameter 1 : parameter 2 : parameter 3 …. : parameter n  | pipe 2 : parameter 1 : parameter 2 : parameter 3 …. : parameter n | pipe 3 : parameter 1 : parameter 2 : parameter 3 …. : parameter n | ……… pipe n : parameter 1 : parameter 2 : parameter 3 …. : parameter n

Let’s have a look at the built-in pipes and then we will go through the custom pipe as well.

Case Conversion Pipes

Built-in Angular Pipes for Case Conversion

  • UpperCasePipe: UpperCasePipe is used to transforms text to uppercase.

Example
{{name | uppercase}}

  • LowerCasePipe: UpperCasePipe is used to transforms text to lowercase.

Example
{{name | lowercase}}

  • TitleCasePipe: TitleCasePipe is used to transforms text to title case.

Example
{{name | titlecase}}

To understand it in a better way let’s create an Angular app. I am going to create an Angular App using Visual Studio 2017 as IDE. You can choose any IDE.

Add a component “AngularPipesDemoComponent”, I will be using the same component for all pipe demos.

component.ts

public name: string = 'bANketEShVar NarAYan';

component.html 

  1. <div class="row" style="margin-bottom:5px">  
  2.     <div class="col-md-6 col-md-offset-3"><span style="font-size:24px; font-weight:bold"> Case Conversion Example</span></div>  
  3. </div>  
  4.   
  5. <table class="table table-inverse" style="font-size:20px; font-weight:400">  
  6.     <thead class="bg-primary">  
  7.         <tr>  
  8.             <th>Original Text</th>  
  9.             <th>Lower Case</th>  
  10.             <th>Upper Case</th>  
  11.             <th>Title Case</th>  
  12.         </tr>  
  13.     </thead>  
  14.     <tbody>  
  15.         <tr class="bg-success">  
  16.             <td>{{name}}</td>  
  17.             <td>{{name | lowercase}}</td>  
  18.             <td>{{name | uppercase}}</td>  
  19.             <td>{{name | titlecase}}</td>  
  20.         </tr>  
  21.     </tbody>  
  22. </table>  

Output

Angular Pipes
DatePipe

DatePipe can be used to convert a date to desired date or time format based on locale and time zones.

Syntax

date_expression | date[:format[:timezone[:locale]]]

*.component.ts
currentdate = Date.now(); 

*.component.html 

  1. <h3>Date Formats Sample</h3>  
  2. <p>Today is :{{currentdate | date}}</p>  
  3.   
  4. <p>Today is : {{currentdate | date:'fullDate'}}</p>  
  5. <p>Current time is : {{currentdate | date:'shortTime'}}</p>  
  6. <p>Current Date is: {{currentdate | date:'dd-MMMM-yyyy'}}</p>  

Output

Angular Pipes
PercentPipe

PercentPipe is used to display data in percent. i.e 0.51 is displayed as 51 percent.

Syntax

number_expression | percent[:{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} [:locale]]

where minIntegerDigits, minFractionDigits and maxFractionDigits have default values 1,0 and 3 respectively. 

component.ts

  1. mynumber: number = 0.51003003039303033030;  
  2. mynumber2: number = 0.05;  

component.html

  1. <div class="row" style="margin-bottom:5px">  
  2. <div class="col-md-6 col-md-offset-3"><span style="font-size:24px; font-weight:bold">PercentPipe (percent) Example</span></div>  
  3. </div>  
  4. <table class="table table-inverse" style="font-size:20px; font-weight:400">  
  5.     <thead class="bg-primary">  
  6.         <tr>  
  7.             <th>#</th>  
  8.             <th>Original Data</th>  
  9.             <th>Format 1</th>  
  10.             <th>Format 2</th>  
  11.             <th>Format 3</th>  
  12.         </tr>  
  13.     </thead>  
  14.     <tbody>  
  15.         <tr class="bg-success">  
  16.             <th scope="row">1</th>  
  17.             <td>{{mynumber}}</td>  
  18.             <td>{{ mynumber|percent}}</td>  
  19.             <td>{{ mynumber|percent:'2.4-8'}}</td>  
  20.             <td>{{ mynumber|percent:'5.4-8':'in'}}</td>  
  21.         </tr>  
  22.         <tr class="bg-warning">  
  23.             <th scope="row">2</th>  
  24.             <td>{{mynumber2}}</td>  
  25.             <td>{{ mynumber2|percent}}</td>  
  26.             <td>{{ mynumber2|percent:'2.4-8'}}</td>  
  27.             <td>{{ mynumber2|percent:'5.4-8':'in'}}</td>  
  28.         </tr>  
  29.     </tbody>  
  30. </table>  

Output

Angular Pipes

DecimalPipe

DecimalPipe is used to display data in decimal with custom formatting.

Syntax

number_expression | number[:{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} [:locale]]

where minIntegerDigits, minFractionDigits and maxFractionDigits have default values 1,0 and 3 respectively. 

component.ts 

  1. mynumber: number = 0.51003003039303033030;  
  2. mynumber2: number = 0.05;  

component.html

  1. <div class="row" style="margin-bottom:5px">  
  2. <div class="col-md-6 col-md-offset-3"><span style="font-size:24px; font-weight:bold">DecimalPipe (number) Example</span></div>  
  3. </div>  
  4. <table class="table table-inverse" style="font-size:20px; font-weight:400">  
  5.     <thead class="bg-primary">  
  6.         <tr>  
  7.             <th>#</th>  
  8.             <th>Original Data</th>  
  9.             <th>Format 1</th>  
  10.             <th>Format 2</th>  
  11.             <th>Format 3</th>  
  12.         </tr>  
  13.     </thead>  
  14.     <tbody>  
  15.         <tr class="bg-success">  
  16.             <th scope="row">1</th>  
  17.             <td>{{mynumber}}</td>  
  18.             <td>{{ mynumber|number}}</td>  
  19.             <td>{{ mynumber|number:'2.4-8'}}</td>  
  20.             <td>{{ mynumber|number:'5.4-8':'in'}}</td>  
  21.         </tr>  
  22.         <tr class="bg-warning">  
  23.             <th scope="row">2</th>  
  24.             <td>{{mynumber2}}</td>  
  25.             <td>{{ mynumber2|number}}</td>  
  26.             <td>{{ mynumber2|number:'2.4-8'}}</td>  
  27.             <td>{{ mynumber2|number:'5.4-8':'in'}}</td>  
  28.         </tr>  
  29.     </tbody>  
  30. </table>  

Output

Angular Pipes

CurrencyPipe
 

CurrencyPipe displays data with currency format.

Syntax

number_expression | currency[:currencyCode[:display[:{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} [:locale]]]] 

Example

  1. {{ mynumber|currency:'INR'}}  
  2. {{ mynumber|currency:'INR':'code'}}  

component.ts 

  1. mynumber: number = 0.51003003039303033030;  
  2. mynumber2: number = 0.05;  

component.html

  1. <h3> CurrencyPipe Usage Example</h3>  
  2. <p>Original data: <b>{{mynumber}}</b></p>  
  3. <p>Default Format: <b>{{ mynumber|currency}}</b></p><br />  
  4.   
  5. <div class="bd-example">  
  6.     <table class="table table-inverse">  
  7.         <thead class="bg-primary">  
  8.             <tr>  
  9.                 <th>#</th>  
  10.                 <th>Formats</th>  
  11.                 <th>Format 1</th>  
  12.                 <th>Format 2</th>  
  13.             </tr>  
  14.         </thead>  
  15.         <tbody>  
  16.             <tr class="bg-success">  
  17.                 <th scope="row">1</th>  
  18.                 <td>USD Formats</td>  
  19.                 <td>{{ mynumber|currency:'USD'}}</td>  
  20.                 <td>{{ mynumber|currency:'USD':'code'}}</td>  
  21.             </tr>  
  22.   
  23.             <tr class="bg-warning">  
  24.                 <th scope="row">2</th>  
  25.                 <td>CAD Formats</td>  
  26.                 <td>{{ mynumber|currency:'CAD'}}</td>  
  27.                 <td>{{ mynumber|currency:'CAD':'code'}}</td>  
  28.             </tr>  
  29.   
  30.             <tr class="bg-danger">  
  31.                 <th scope="row">3</th>  
  32.                 <td>INR Formats</td>  
  33.                 <td>{{ mynumber|currency:'INR'}}</td>  
  34.                 <td>{{ mynumber|currency:'INR':'code'}}</td>  
  35.             </tr>  
  36.         </tbody>  
  37.     </table>  
  38. </div>  

Output

Angular Pipes

SlicePipe

SlicePipe is used to return a substring or a subset of a string array. 

Syntax

expression | slice:start[:end] 

Examples

  1. {{text | slice:2}}  
  2. {{text | slice:-3:-2}}  

component.ts

public text: string = 'ABCDEFGHIJKLMN'; 

component.html 

  1. <h4>Original Text</h4>  
  2. <h4 class="bg-primary text-white">{{text}}</h4>  
  3. <hr />  
  4.   
  5. <h4>Skip First 2 Character from string</h4>  
  6. <h4 class="bg-primary text-white">{{text | slice:2}}</h4>  
  7.   
  8. <hr />  
  9. <h4>Get First 5 Characters from string</h4>  
  10. <h4 class="bg-primary text-white">{{text | slice:0:5}}</h4>  
  11.   
  12. <hr />  
  13. <h4>Get Last 2 Character from string</h4>  
  14. <h4 class="bg-primary text-white">{{text | slice:-2}}</h4>  
  15.   
  16. <h4>Get Third Last Character from string</h4>  
  17. <h4 class="bg-primary text-white">{{text | slice:-3:-2}}</h4>  

Output

Angular Pipes

JsonPipe

JsonPipe converts a value into JSON string. 

Syntax

expression | json

Example

{{countries | json}}

component.ts 

  1. public countries =  
  2.    [{ "id": 1, "country""Russia" },  
  3.     { "id": 2, "country""Canada" },  
  4.     { "id": 3, "country""China" },  
  5.     { "id": 4, "country""Brazil" },  
  6.     { "id": 5, "country""India" }];  

component.html

  1. <h4>Render all 5 countries</h4>  
  2. <pre>{{countries | json}}</pre>   

Output

Angular Pipes

Using ‘slice’ and ‘json’ pipes together

As I said at the start of this article, we can use multiple pipes with the same expression. So, let’s use ‘slice’ and ‘json’ pipes together.

component.html

  1. <h4>Render countries 2<sup>nd</sup> and 3<sup>rd</sup> elements</h4>  
  2. <pre>{{countries | slice:1:3 | json }}</pre>  

Output

Angular Pipes

Custom pipes

So far, we have seen a lot of built-in pipes. Let’s have a look at how to create custom pipes.

Custom Pipe: AlternateCase

I am going to create my first custom pipe. So far, we have seen in-built case conversion pipes for lower case, upper case and title case. Now, create a custom pipe for the alternate case.

Step 1 - Add a typescript file

Add a typescript file with name “alternatecase.pipe.ts” for creating custom pipe alternatecase.

Step 2 - import Pipe and PipeTransform

Go to the file “alternatecase.pipe.ts” and import Pipe and PipeTransform from '@angular/core' . 

import {Pipe, PipeTransform } from '@angular/core';

Step 3

Write a class for alternatecase pipe and implement the transform method of PipeTransform interface.

  1. export class AlternateCasePipe implements PipeTransform {  
  2.     transform(value: string): string {  
  3.         if (!value) return value;  
  4.         return value.split(/\b/g).map(word => alternatecaseWord(word)).join('');  
  5.     }  
  6. }  
  7.   
  8. function alternatecaseWord(word: string) {  
  9.   
  10.     if (!word) return word;  
  11.     let altString = '';  
  12.   
  13.     for (var i = 0; i < word.length; i++) {  
  14.   
  15.         if (i % 2 == 0) {  
  16.             altString += word[i].toUpperCase();  
  17.         }  
  18.         else {  
  19.             altString += word[i].toLowerCase();  
  20.         }  
  21.     }  
  22.   
  23.     return altString;  
  24. }  

Step 4 - Decorate the class with @Pipe decorator

@Pipe({ name: 'alternatecase' })

Following is the complete code for alternatecase.pipe.ts.

  1. import { Pipe, PipeTransform } from '@angular/core';  
  2.   
  3. @Pipe({ name: 'alternatecase' })  
  4. export class AlternateCasePipe implements PipeTransform {  
  5.     transform(value: string): string {  
  6.         if (!value) return value;  
  7.         return value.split(/\b/g).map(word => alternatecaseWord(word)).join('');  
  8.     }  
  9. }  
  10.   
  11. function alternatecaseWord(word: string) {  
  12.   
  13.     if (!word) return word;  
  14.     let altString = '';  
  15.   
  16.     for (var i = 0; i < word.length; i++) {  
  17.   
  18.         if (i % 2 == 0) {  
  19.             altString += word[i].toUpperCase();  
  20.         }  
  21.         else {  
  22.             altString += word[i].toLowerCase();  
  23.         }  
  24.     }  
  25.   
  26.     return altString;  
  27. }  

Step 5 - add AlternateCasePipe in declarations section of app.shared.module.ts

Go to the file app\app.shared.module.ts and add the following highlighted lines.

Angular Pipes

Code Snippet 

  1. import { AlternateCasePipe } from '../app/customPipes/alternatecase.pipe';  
  2.   
  3. @NgModule({  
  4.     declarations: [  
  5.         AppComponent,  
  6.         NavMenuComponent,  
  7.         CounterComponent,  
  8.         FetchDataComponent,  
  9.         HomeComponent,  
  10.         AngularPipesDemoComponent,  
  11.         CaseConversionExampleComponent,  
  12.         AlternateCasePipe  
  13.     ],  
  14.     imports: [  
  15.         CommonModule,  

Demo Alternate Case Pipe

So finally, we have created a custom pipe for the alternate case. Now, we should go for a demo of alternate case pipe.

Go to the component where we have written the code of demo of other pipes and add the following lines.

component.ts

  1. public name: string = 'banketeshvar narayan';  
  2. public text: string = 'ABCDEFGHIJKLMN' 

component.html

  1. <h4 class="bg-primary text-white">Custom Pipe : Alternate Case Demo</h4>  
  2.   
  3. <h4>Original Text:  <b class="text-success">{{name}}</b> </h4>  
  4. <h4>Formatted Text: <b class="text-primary">{{name | alternatecase}}</b></h4>  
  5.   
  6. <br />  
  7. <h4>Original Text:  <b class="text-success">{{text}}</b></h4>  
  8. <h4>Formatted Text: <b class="text-primary">{{text | alternatecase}}</b></h4>   

Output

Angular Pipes

Custom Pipe:
Opinion Pipe

So far, we have created a custom pipe to transform a string to the alternate case. Let’s have a look at another example. 

We have the following JSON.

  1. public questions = [  
  2.         { "statement""Statement 1""answer": 1 },  
  3.         { "statement""Statement 2""answer": 2 },  
  4.         { "statement""Statement 3""answer": 3 },  
  5.         { "statement""Statement 4""answer": 4 },  
  6.         { "statement""Statement 5""answer": 5 },  
  7.         { "statement""Statement 6""answer": 6 }  
  8.     ]  

Where answers 1 to 6 represent the opinions 'Very Strongly Agree', 'Strongly Agree', 'Agree’, 'Disagree’,  'Strongly Disagree' and 'Very Strongly Disagree' respectively. Now, we would like to display it on UI.

HTML

  1. <table class="table table-inverse" style="font-size:20px; font-weight:400">  
  2.     <thead class="bg-primary">  
  3.         <tr>  
  4.             <th>Statement</th>  
  5.             <th>Opinion</th>              
  6.         </tr>  
  7.     </thead>  
  8.     <tbody>  
  9.         <tr *ngFor="let question of questions">  
  10.             <td>{{ question.statement }}</td>  
  11.             <td>{{ question.answer }}</td>  
  12.         </tr>  
  13.     </tbody>  
  14. </table>  

Output

 HTML page Output will look like the below screenshot.

Angular Pipes

However, it does not look good. It would be better if we display descriptive text for an opinion. So, let’s create a custom pipe to transform the numeric opinion value to meaningful descriptive text.

Repeat the same steps which have been mentioned for creating alternate case pipe and finally the typescript file will have the following code,

opinion.pipe.ts

  1. import { Pipe, PipeTransform } from '@angular/core'  
  2.   
  3. @Pipe({ name: 'opinion' })  
  4. export class OpinionPipe implements PipeTransform {  
  5.     transform(value: number): string {  
  6.         switch (value) {  
  7.             case 1: return 'Very Strongly Agree'  
  8.             case 2: return 'Strongly Agree'  
  9.             case 3: return 'Agree'  
  10.             case 4: return 'Disagree'  
  11.             case 5: return 'Strongly Disagree'  
  12.             case 6: return 'Very Strongly Disagree'  
  13.             defaultreturn value.toString();  
  14.         }  
  15.     }  
  16. }  

Please do remember to add it to “app.shared.module.ts” file as well.

Now go to the HTML code and replace

<td>{{ question.answer}}</td>

with

<td>{{ question.answer | opinion }}</td>

Now, your HTML page will render a meaningful output. Following is the screenshot of the same.

Angular Pipes