Create Custom Pipe In Angular 2

Introduction

Pipes allow us to change the data inside the template. Normally, a pipe takes the data and transforms this input to the desired output. There are many built-in pipes in Angular 2. Also, we can create custom pipes with Angular 2. In this article, we will learn how to create a custom pipe in Angular 2.

The basic definition or the structure of creating custom pipe is given below.

  1. import {  
  2.     Pipe,  
  3.     PipeTransform  
  4. } from '@angular/core';  
  5. @Pipe({  
  6.     name: 'name of pipe used in markup'  
  7. })  
  8. export class NameofClass implements PipeTransform {  
  9.     transform(value: string, args: string[]): any {  
  10.         //Play with value and argument and return the result  
  11.         return value;  
  12.     }  
  13. }  
  14.   
  15. // This is just a sample script. Paste your real code (javascript or HTML) here.  
  16.   
  17. if ('this_is' == /an_example/) {  
  18.     of_beautifier();  
  19. else {  
  20.     var a = b ? (c % d) : e[f];  
  21. }  
Point to remember while defining pipes
  • The Pipe is a class that contains "pipe" metadata.
  • The Pipe class contains method "transform", which is implemented from “PipeTransform” interface. This method accepts the value and optionally accepts the arguments and converts it to the required format.
  • We can add the required argument to the "transform" method.
  • The @pipe decorator is used to declare Pipe and it is defined in core Angular library, so we need to import this library. This decorator allows us to define the name of Pipe, which is used in HTML markup.
  • The “transform” method can return any type of value. If our Pipe’s return type is decided on run time, we can use “any,” otherwise, we can define specific types like number or string.

Example

Title Case Pipe example

There are built-in pipes available to convert our string to upper case and lower case, but there is no Pipe available for title case (capitalization). Thus, to achieve this, we need to write a Custom Pipe.

Following is the definition of title case Pipe. In this Pipe, we need to pick up all the words in the string and make the first character of the string in upper case and the rest of the characters in lower case.

titlecasepipe.ts

  1. import {  
  2.     Pipe,  
  3.     PipeTransform  
  4. } from '@angular/core';  
  5. @Pipe({  
  6.     name: 'titlecase'  
  7. })  
  8. export class TitleCasePipe implements PipeTransform {  
  9.     transform(value: string, args: string[]): any {  
  10.         if (!value) return value;  
  11.         return value.replace(/\w\S*/g, function(txt) {  
  12.             return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();  
  13.         });  
  14.     }  
  15. }  
The next step is to use this Pipe into our Application. To use the Custom Pipe, we need to import this Pipe into our component.

app.component.ts
  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. //import pipe(s)  
  5. import {  
  6.     TitleCasePipe  
  7. } from './titlecasepipe';  
  8. @Component({  
  9.     selector: 'test-app',  
  10.     pipes: [TitleCasePipe],  
  11.     templateUrl: './app/example.html'  
  12. })  
  13. export class AppComponent {  
  14.     name = "jigneshtrivedi";  
  15. }  
example.html
  1. <div>  
  2.     <h4>Title Case Pipe example</h4>  
  3.     Hello, My name is {{name | titlecase}}  
  4. </div>  
Output

Output

In the next example, I will create Bold Pipe, which converts our text to bold notation.

Bold Pipe example

This Pipe is very simple. From the Pipes, I have returned the input string inside the "b" tag.

TextboldPipe.ts
  1. import {  
  2.     Pipe,  
  3.     PipeTransform  
  4. } from '@angular/core';  
  5. @Pipe({  
  6.     name: 'bold'  
  7. })  
  8. export class BoldPipe implements PipeTransform {  
  9.     transform(value: string): any {  
  10.         return '<b>' + value + '</b>';  
  11.     }  
  12. }  
app.component.ts
  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. //import pipe(s)  
  5. import {  
  6.     BoldPipe  
  7. } from './textboldpipe';  
  8. @Component({  
  9.     selector: 'test-app',  
  10.     pipes: [BoldPipe],  
  11.     templateUrl: './app/example.html'  
  12. })  
  13. export class AppComponent {  
  14.     name = "jigneshtrivedi";  
  15.     myText = "This is my test string.";  
  16. }  
example.html
  1. <div>  
  2.     <h4>Bold Pipe example</h4>  
  3.     Hello, My name is <span [outerHTML]="name | titlecase | bold"></span>  
  4. </div>  
Output

Output

Parameterizing a Pipe

A Pipe may accept n-number of optional parameters to produce the output. Using colon (:), we can supply the parameters to the Pipes, for example date:'dd/MM/yyyy'. If the Pipe accepts multiple parameters, we need to pass all the parameters to separate the values with colons for example slice: 1:5.

In the example given below, I have created Parameterized Custom Pipe. Here, I have created Pipe to limit the words into the string. Suppose, we have a requirement like if text is exceeded by more than 10 characters, we need to show the text up to 10 characters followed by three dots (...). To achieve this, I have create Pipe called "limitwordpipe".

Limit word Pipe example

This Pipe accepts two parameters, one parameter is for number of characters to be shown, when the Pipe applies, and the other for showing tailing characters.

limitwordPipe.ts
  1. import {  
  2.     Pipe,  
  3.     PipeTransform  
  4. } from '@angular/core';  
  5. @Pipe({  
  6.     name: 'limitword'  
  7. })  
  8. export class LimitWordPipe implements PipeTransform {  
  9.     transform(value: string, limit: string, trail: string): any {  
  10.         letlimitChar = limit != null ? parseInt(limit) : 10;  
  11.         lettrailString = (trail != null) ? trail : '...';  
  12.         returnvalue.length > limitChar ? value.substring(0, limitChar) + trailString : value;  
  13.     }  
  14. }  
  15. app.component.ts  
  16. import {  
  17.     Component  
  18. } from '@angular/core';  
  19. //import pipe(s)  
  20. import {  
  21.     LimitWordPipe  
  22. } from './limitwordpipe';  
  23. @Component({  
  24.     selector: 'test-app',  
  25.     pipes: [LimitWordPipe],  
  26.     templateUrl: './app/example.html'  
  27. })  
  28. export class AppComponent {  
  29.     name = "jigneshtrivedi";  
  30.     myText = "This is my test string.";  
  31. }  
  32. example.html <  
  33.     div >  
  34.     <  
  35.     h4 > Limit word Pipe example < /h4>  
  36. With no arg.: {  
  37.         {  
  38.             myText | limitword  
  39.         }  
  40.     } < br / >  
  41.     Limit to 15 character: {  
  42.         {  
  43.             myText | limitword: 15  
  44.         }  
  45.     } < br / >  
  46.     Limit to 15 character with trail character: {  
  47.         {  
  48.             myText | limitword: 15: '***'  
  49.         }  
  50.     } < br / >  
  51.     <  
  52.     /div>  
Output

Output

Register Pipe globally

We can also register Pipe application-wide. Some of the Pipes are used application-wide; i.e., used in most all of our components. In this case, it is very difficult to inject Pipe to each and every component and it is a very tedious job. Instead of doing this, we can inject our Pipe during bootstrapping of the Application.

In the example given below, I have to import all three Pipes which were created early in this article for bootstrapping module (app.module in our case). Thus, these pipes are available in every component of the Application.

App.module.ts
  1. import {  
  2.     NgModule  
  3. } from '@angular/core';  
  4. import {  
  5.     BrowserModule  
  6. } from '@angular/platform-browser';  
  7. import {  
  8.     FormsModule  
  9. } from '@angular/forms';  
  10. import {  
  11.     AppComponent  
  12. } from './app.component';  
  13. //import pipe(s)  
  14. import {  
  15.     TitleCasePipe  
  16. } from './titlecasepipe';  
  17. import {  
  18.     BoldPipe  
  19. } from './textboldpipe';  
  20. import {  
  21.     LimitWordPipe  
  22. } from './limitwordpipe';  
  23. @NgModule({  
  24.     imports: [BrowserModule, FormsModule],  
  25.     declarations: [AppComponent, TitleCasePipe, BoldPipe, LimitWordPipe], //declare pipe(s)  
  26.     bootstrap: [AppComponent],  
  27. })  
  28. export class AppModule {}  
App.component.ts
  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. @Component({  
  5.     selector: 'test-app',  
  6.     templateUrl: './app/example.html'  
  7. })  
  8. export class AppComponent {  
  9.     name = "jigneshtrivedi";  
  10.     myText = "This is my test string.";  
  11. }  
Example.html
  1. <h4>Custom pipes in Angular 2 </h4>  
  2. <div>  
  3.     <h4>Title Case Pipe example</h4>  
  4.     Hello, My name is {{name | titlecase}}  
  5. </div>  
  6. <br/>  
  7. <div>  
  8.     <h4>Bold Pipe example</h4>  
  9.     Hello, My name is <span [outerHTML]="name | titlecase | bold"></span>  
  10. </div>  
  11. <div>  
  12.     <h4>Limit word Pipe example</h4>  
  13.     With no arg.: {{myText | limitword }} <br/> Limit to 15 character: {{myText | limitword:15}} <br/> Limit to 15 character with trail character: {{myText | limitword:15:'***'}} <br/>  
  14. </div>  
Output

Output

Conclusion

There are many predefined pipes which are available but it is necessary to create Custom Pipe to achieve the desired functionality.This article help us to know how we can create Custom Pipe in Angular 2.

Note

Here, I have not included the dependency of the example Project. To run Project, you need to perform "npm install" command to download the project dependency.


Similar Articles