Angular Custom Pipe Example

Pipe

PipeTransform

@Pipe

PipeTransform

transform()

transform()

@Pipe

PipeTransform

transform()

@NgModule

@Pipe

Software Used

Diagram to Create Custom Pipe

MyJSONPipe

Pipe

PipeTransform

@Pipe

name

PipeTransform

transform()

transform()

transform()

any

transform()

transform()

transform()

transform()

Create Component and Module

import {Component} from '@angular/core'; import {Person} from './person'; import {Company} from './company'; @Component({ selector: 'app-root', template: ` <h3>1. Using welcome Pipe</h3> {{person.name | welcome}} <br/> <h3>2. Using strformat Pipe</h3> {{message | strformat:'+'}} <h3>3. Using division Pipe</h3> <div>Dividend: <input [(ngModel)]="dividend"> </div> <div>Divisor: <input [(ngModel)]="divisor"> </div> <p> Division Result: {{dividend | division: divisor}} </p> <h3>4. Using repeat Pipe</h3> {{person.name | repeat:10}} <h3>5. Using myjson Pipe</h3> <pre>{{person | myjson}}</pre> <pre>{{person | myjson:0:'id,age'}}</pre> <pre>{{person | myjson:1:'id,name'}}</pre> <h3>6. Using myuppercaseone and myuppercasetwo Pipe</h3> {{message | myuppercaseone}} <br/> {{message | myuppercasetwo:'+'}} <br/> <h3>7. Chaining of Custom Pipes</h3> {{person.name | repeat:5 | myuppercaseone}} <h3>8. Using Pure and Impure Pipe</h3> Company Name: <input [(ngModel)] ="compName"/> {{compName}} <br/>Location: <input [(ngModel)] ="compLocation"/> {{compLocation}} <br/><br/><button (click)="updateCompany()">Update Existing</button> <button (click)="createCompany()">Create New </button> <br/><b>a. Using Pure Pipe : companyone</b><br/><br/> {{company | companyone}} <br/><br/><b>b. Using Impure Pipe : companytwo</b><br/><br/> {{company | companytwo}} ` }) export class CustomPipeComponent { //For welcome, repeat, myjson Pipe person: Person = new Person(1, 'Ram', 30); //For strformat, myuppercaseone and myuppercasetwo Pipe message: string = "My name is Mahesh"; //For division Pipe dividend : number = 23; divisor : number = 7; //For pure and impure pipe compName:string = "ABCD LTD"; compLocation:string = "Varanasi"; company = new Company(this.compName, this.compLocation); //Impure change because there is no change in object reference: company //Impure pipe will run again and Pure pipe will do nothing. updateCompany() { this.company.cname = this.compName; this.company.location = this.compLocation; } //Pure change because there is change in object reference: company //Impure pipe and Pure pipe both will run again. createCompany() { this.company = new Company(this.compName, this.compLocation); } }

export class Company { constructor(public cname:string, public location:string) { } }

export class Person { constructor(public id:number, public name:string, public age:number) { } }

import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {FormsModule} from '@angular/forms'; import {CustomPipeComponent} from './custompipe.component'; import {WelcomePipe} from './welcome.pipe'; import {StrFormatPipe} from './strformat.pipe'; import {MyUppercaseOnePipe} from './myuppercaseone.pipe'; import {MyUppercaseTwoPipe} from './myuppercasetwo.pipe'; import {DivisionPipe} from './division.pipe'; import {RepeatPipe} from './repeat.pipe'; import {MyJSONPipe} from './myjson.pipe'; import {CompanyOnePipe} from './companyone.pipe'; import {CompanyTwoPipe} from './companytwo.pipe'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [WelcomePipe, StrFormatPipe, MyUppercaseOnePipe, MyUppercaseTwoPipe, DivisionPipe, RepeatPipe, MyJSONPipe, CompanyOnePipe, CompanyTwoPipe, CustomPipeComponent], bootstrap: [CustomPipeComponent] }) export class AppModule { }

@Pipe Decorator and PipeTransform Interface

Pipe

PipeTransform

@Pipe

Pipe

@Pipe

Pipe

interface Pipe { name : string pure : boolean }

Pipe

@Pipe

@Pipe({ name: 'welcome' })

welcome

welcome

PipeTransform

PipeTransform

interface PipeTransform { transform(value: any, ...args: any[]) : any }

transform()

any

transform()

any

PipeTransform

transform()

Create Simple Custom Pipe

WelcomePipe

Pipe

PipeTransform

WelcomePipe

@Pipe

WelcomePipe

PipeTransform

transform()

PipeTransform

transform()

WelcomePipe

@NgModule

module.ts

WelcomePipe

import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'welcome' }) export class WelcomePipe implements PipeTransform { transform(value: string): string { let message = "Welcome to " + value; return message; } }

name

@Pipe

welcome

custompipe.component.ts

{{person.name | welcome}}

Welcome to Ram

Pass Arguments in Custom Pipe

transform()

transform()

transform()

StrFormatPipe

import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'strformat' }) export class StrFormatPipe implements PipeTransform { transform(value: string, seperator: string): string { let result = value.split(' ').join(seperator); return result; } }

name

@Pipe

strformat

transform()

strformat

transform()

custompipe.component.ts

{{message | strformat:'+'}}

My+name+is+Mahesh

DivisionPipe

import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'division' }) export class DivisionPipe implements PipeTransform { transform(dividend: number, divisor: number): number { let num = dividend / divisor; return num; } }

@Pipe

transform()

custompipe.component.ts

<div>Dividend: <input [(ngModel)]="dividend"> </div> <div>Divisor: <input [(ngModel)]="divisor"> </div> <p> Division Result: {{dividend | division: divisor}} </p>

RepeatPipe

import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'repeat' }) export class RepeatPipe implements PipeTransform { transform(word: string, frequency: number): string { let cnt = 1; let strResult= word; while (cnt < frequency) { strResult = strResult + ' ' + word; cnt = cnt + 1; } return strResult; } }

@Pipe

transform()

custompipe.component.ts

{{person.name | repeat:10}}

Ram Ram Ram Ram Ram Ram Ram Ram Ram Ram

MyJSONPipe

import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'myjson' }) export class MyJSONPipe implements PipeTransform { transform(value: any, prettyprint?: number, fields?: string): string { let array = (fields == null? null : fields.split(',')); let pp = (prettyprint == null ? 0 : prettyprint); let result = JSON.stringify(value, array, pp); return result; } }

@Pipe

transform()

any

custompipe.component.ts

<pre>{{person | myjson}}</pre> <pre>{{person | myjson:0:'id,age'}}</pre> <pre>{{person | myjson:1:'id,name'}}</pre>

{"id":1,"name":"Ram","age":30} {"id":1,"age":30} { "id": 1, "name": "Ram" }

Use Built-in Pipe in Custom Pipe

UpperCasePipe

UpperCasePipe

UpperCasePipe

UpperCasePipe

PipeTransform

transform()

MyUppercaseOnePipe

MyUppercaseOnePipe

PipeTransform

UpperCasePipe

PipeTransform

MyUppercaseOnePipe

import {Pipe} from '@angular/core'; import {UpperCasePipe} from '@angular/common'; @Pipe({ name: 'myuppercaseone' }) export class MyUppercaseOnePipe extends UpperCasePipe{ transform(value: string): string { let result = super.transform(value); result = result.split(' ').join('-'); return result; } }

UpperCasePipe

CommonModule

UpperCasePipe

transform()

UpperCasePipe

transform()

let result = super.transform(value);

super

transform()

MyUppercaseOnePipe

transform()

UpperCasePipe

custompipe.component.ts

{{message | myuppercaseone}}

MY-NAME-IS-MAHESH

UpperCasePipe

PipeTransform

transform()

UpperCasePipe

transform()

MyUppercaseTwoPipe

import {Pipe, PipeTransform} from '@angular/core'; import {UpperCasePipe} from '@angular/common'; @Pipe({ name: 'myuppercasetwo' }) export class MyUppercaseTwoPipe implements PipeTransform{ transform(value: string, seperator: string): string { let upipe = new UpperCasePipe(); let result = upipe.transform(value); result = result.split(' ').join(seperator); return result; } }

custompipe.component.ts

{{message | myuppercasetwo:'+'}}

MY+NAME+IS+MAHESH

Chaining of Custom Pipes

{{person.name | repeat:5 | myuppercaseone}}

RAM-RAM-RAM-RAM-RAM

Pure and Impure Custom Pipe and Change Detection

pure: true

@Pipe

pure

@Pipe

@Pipe({ name: 'companyone' })

@Pipe

pure: true

@Pipe({ name: 'companytwo', pure: false })

pure

transform()

Company

string

import {Pipe, PipeTransform} from '@angular/core'; import {Company} from './company'; @Pipe({ name: 'companyone' }) export class CompanyOnePipe implements PipeTransform { transform(obj: Company): string { let output = obj.cname+' : '+ obj.location; return output; } }

import {Pipe, PipeTransform} from '@angular/core'; import {Company} from './company'; @Pipe({ name: 'companytwo', pure: false }) export class CompanyTwoPipe implements PipeTransform { transform(obj: Company): string { let output = obj.cname+' : '+ obj.location; return output; } }

Company

Company

compName:string = "ABCD LTD"; compLocation:string = "Varanasi"; company = new Company(this.compName, this.compLocation);

company

Company

company

createCompany() { this.company = new Company(this.compName, this.compLocation); }

company

company

updateCompany() { this.company.cname = this.compName; this.company.location = this.compLocation; }

company

custompipe.component.ts

Company Name: <input [(ngModel)] ="compName"/> {{compName}} <br/>Location: <input [(ngModel)] ="compLocation"/> {{compLocation}} <br/><br/><button (click)="updateCompany()">Update Existing</button> <button (click)="createCompany()">Create New </button> <br/><b>a. Using Pure Pipe : companyone</b><br/><br/> {{company | companyone}} <br/><br/><b>b. Using Impure Pipe : companytwo</b><br/><br/> {{company | companytwo}}

ABCD LTD : Varanasi

ABCD LTD11 : Varanasi11

updateCompany()

company

company

ABCD LTD1111 : Varanasi1111

ABCD LTD1111 : Varanasi1111

createCompany()

company

Run Application

Reference

Download Source Code

This page will walk through Angular custom pipe example. We can write our own custom pipe and that will be used in the same way as angular built-in pipes. To create custom pipe, angular providesandinterfaces. Every pipe is decorated withwhere we define the name of our custom pipe. Every pipe will implementinterface. This interface providesmethod and we have to override it in our custom pipe class.method will decide the input types, number of arguments and its types and output type of our custom pipe. We perform the following steps to create a custom pipe.Step 1: Create a typescript class.Step 2: Decorate the class usingStep 3: Implementinterface.Step 4: Overridemethod.Step 5: Configure the class in application module withStep 6: Ready to use our custom pipe anywhere in application.On the basis of change detention, angular provides two types of pipes.: This will run only for pure changes in component properties.: This will run for any type of changes in component properties.Pure and impure pipe are declared usingdecorator. Here on this page we will create custom pipes with and without arguments. We will also create custom pipe using angular built-in pipes. We will also provide example of pure and impure pipe. Now find the angular custom pipe tutorial with examples step by step using TypeScript.Find the software used in our demo.1. Angular 9.1.112. Node.js 12.5.03. NPM 6.9.0Here we are creating a custom pipe named as. This will convert a given object input into JSON format. Our pipe will accept input of any type of object. Our custom pipe will accept two arguments. Find the demo by diagram.We are doing following steps to create our custom pipe.1. Create a typescript class, for exampleand importandinterface.2. Decorate class usingand assign pipe name tometadata for example3. Implementinterface and overridemethod.4. Our custom pipe needs two arguments. Somethod has three parameters. First parameter is for pipe input and the rest two is for pipe arguments.5. Inmethod first parameter is oftype, sopipe will accept any type of object as an input.6. Inmethod, second parameter is of number type. This will be used to decide whetherpipe will give pretty print output or not. If its value is 0, then no pretty print and if 1 or greater than 1, then result will be pretty print when usingpipe withtag.7. Inmethod, third parameter provide the fields of input object that will be involved in JSON output.8. We are using return type ofmethod as string, sowill give output as string.9. Inmethod second and third parameter is optional. If we do not provide any argument topipe then all the fields will be involved in JSON format and the output will be no pretty print.Find the component that is using our custom pipes.We have also created some classes that will act as input for custom pipes.Now find the module, main and index.html used in our example.To create custom pipe we need to understand angularandAPI.decorator is ainterface. A typescript class is decorated byto create an angular custom pipe. Find theinterface from the angular Pipe API document.: Assign custom pipe name.: Assign true or false. Default is true. If true then pipe will be a pure pipe otherwise impure pipe. So by default all pipes are pure pipe.For example we will useinterface asdecorator as follows.Here custom pipe name isand as we know that by defaultmetadata value is, sopipe will be a pure pipe.is an angular interface. To create a custom pipe our typescript class has to implementinterface. It has been defined as follows in angular PipeTransform API document.In the above interface a methodhas been defined. It accepts minimum one argument and maximum any number of arguments. The parameter type is. It means we can pass any type of object.method returns value of type. To create custom pipe our typescript class will implementand overridemethod. The use of parameters is as follows.1. First parameter (value: any): This is the value in left side of our pipe operator (|).2. Optional parameters: These are arguments used with pipe in right side of pipe operator (|).3. Value returned by method: This is the value that is the output of our custom pipe.Now we will start creating our custom pipe. Here we will create a simple custom pipe named as. The syntax is as follows.We will pass a person name foras string and output will be a welcome message. Now follow the steps to create ourpipe.: Create a typescript class named as: Importandinterface from angular core module.: Decoratewith. Itsmetadata will define custom pipe name.will implementinterface.: Overridemethod ofinterface. The parameter ofcan be of any type. In our example we are using string data type and return type is also a string. Here we will perform task which needs to be done by our custom pipe and return the result. This is the result which will be returned by custom pipe.: To make custom pipe available at application level, declareindecorator. In our example module file isFind theclass.Themetadata ofdecorator has the valueand that will be the name of our custom pipe. In ourfile we are usingpipe as given below.Now we will discuss some custom pipes that will accept arguments. To facilitate custom pipe to accept arguments we have to use optional parameters inmethod while creating custom pipe API. If we want one argument with custom pipe then use one optional parameter inmethod. If we want two arguments with custom pipe then use two optional parameters inmethod and so on. Now find our custom pipes that are using arguments.CreateCustom PipeFind the syntax.Thewill format the given string expression. The spaces between words will be replaced by given separator. Now find the typescript classthat will createpipe.Themetadata ofdecorator has the valueand that will be the name of our custom pipe. We will observe that inmethod first parameter is a string and this will be used by. Second parameter is also a string and this will be used bypipe to pass arguments. In our example argument is string value given by. Nowmethod has return type as string, so the output of our pipewill be a string.In ourfile we are usingpipe as given below.CreateCustom PipeUsingcustom pipe we will divide a number by a given number. Find the syntax.Find the description.: An expression that will return a number and that will be dividend.: This number is the argument of our pipe that will be used as divisor.Now find the typescript classthat will createpipe.Custom pipe name is assigned tometadata ofdecorator. Here custom pipe name is. Inmethod, there are two parameters of number type. First parameter is for expression used with pipe operator and second parameter is used for pipe argument. Return type of method is also a number, sopipe operator will give output as number.In ourfile we are usingpipe as given below.Here dividend and divisor values are input by user. Pure pipe and impure pipe both detect changes immediately for component string property value changes. So whenever there will be change in value of component propertyand, our custom pipewill run every time. Find the output print screen.CreateCustom PipeWe are creating apipe. This pipe will repeat a given word. This will be repeated as many times as given frequency. Find the syntax.Find the typescript classthat will createpipe.decorator has defined the pipe name as. The methodhas two parameters. One is of string type and second is of number type. First parameter is forand second parameter is forIn ourfile we are usingpipe as given below.CreateCustom PipeHere we are creatingcustom pipe. This pipe will convert an expression into JSON format. It will accept two arguments. Find the syntax.Find the description.: Expression that will be converted into JSON format. It can be primitive data type or any object.: If the value is 0, then no pretty print and if the value is 1 or greater than 1, then we will get pretty print JSON format.: If no fields are provided then all the fields of object will take part in JSON format, if specified then only those fields will take part in JSON format.If no argument is passed thenwill convert the given object into JSON format with all fields and without pretty print. Now find the typescript classthat will createpipe.The name of custom pipeis provided indecorator. The methodhas three parameters. First parameter is oftype. It means any type of object can be passed to convert into JSON format. The rest two parameters are pipe arguments. Pretty print of JSON format also requirestag while usingpipe.In ourfile we are usingpipe as given below.Custom pipe can also use angular built-in pipe such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe. In our example we will createandpipe. Both pipes will usebuilt-in pipe. There are two ways to usein our custom pipes.Extendingbuilt-in pipe class:is an angular built-in pipe. It implementsinterface and overridemethod as we do in our custom pipes. Here we will create our custom pipe class named as. This time our classwill not implementbecause it will extendbuilt-in pipe and that is already implementinginterface. Now find theclass.is the API of, so we need to importclass from angularpackage. Here we are overridingmethod from, so we cannot change number of parameters and types inmethod. Now find the line of code.Usingkeyword we call the parent class method. The value passed tomethod ofclass is first processed bymethod ofclass and then we perform our changes and then we return the final result.In ourfile we are usingpipe as given below.Using object ofbuilt-in pipe class:We can also use built-in pipe in our custom pipe by creating object of built-in pipe API. Here we will create our custom pipe as usual by implementingand withinmethod we will use parameters and their types according to our requirements. To process the data bypipe, we will create the object of it and pass the data to itsmethod. Now find theclass.In ourfile we are usingpipe as given below.Chaining of custom pipes is using more than one pipe together. The output of first pipe will be the input for next pipe and so on. Find the example.In the above code snippet we are using two custom pipesand. Firstpipe will run and then its output will be the input forpipe. Find the output.Angular provides pure and impure pipes on the basis of change detection. Here we will discuss pure and impure pipes with examples.Angular uses a change detection process for changes in data-bound values. Change detection runs after every keystroke, mouse move, timer tick, and server response. In case of pipe, angular picks a simpler, faster change detection algorithm.By default all pipes are pure pipe. Pure pipes are those pipes that haveindecorator while creating pipe class. If we have not usedmetadata then its default value will beindecorator. Pure pipes executes only for pure changes in its input values.Find the pure changes.Change to a primitive input values such as String, Number, Boolean.Change to object reference of Date, Array, Function, Object.Above changes are pure changes. If the input values used with pure pipe, comes under the pure changes then pipe will run again to give output accordingly. Pure pipe is created as follows.By defaultdecorator is usingImpure pipes will run for every component change detection cycle. So it is obvious that impure pipes will also run for pure changes. Impure pipe will run for every keystroke or mouse move. So the conclusion is that impure pipe will run a lot and hence we should take care while using impure pipe because it may reduce performance of the application and can destroy user experience. Impure pipe is created as follows.Make sure that metadatahas been assigned withboolean value.Now we will discuss an example of pure and impure pipe. We will see that pure pipe will run only for pure changes whereas impure pipe will run for every type of changes in component properties. We will start by creating pure and impure pipes whosemethod will useclass as parameter type andas return type.Find the pure pipe named asNow find the impure pipe named asWe will observe thatandboth pipes are doing same task. The only difference is thatis a pure pipe andis an impure pipe.Now we will code scenarios for pure and impure changes inobject. Suppose we have createdobject as follows.Pure change inobject by changing its: To change the reference we will create a new object ofclass and assign it to component propertyas follows.When we call the above method then pure and impure both pipes will run. It meansandboth pipe will run again.Impure change inobject by updating its property values: To generate the scenario of impure change, we will update the property value of ourobject as follows.When we call the above method then only impure pipe will run. It meanspipe will not run again butpipe will run again for the changes inobject.Now find the below code fromfile.Initially both text box will be populated with following values.Company Name : ABCD LTDLocation: Varanasi: Change the text box values as follows.Company Name : ABCD LTD11Location: Varanasi11Now click onbutton. Output ofpipe will be as follows.And output ofpipe will be as follows.Let us understand what is happening now. When we click onbutton thenwill execute and performs impure change inobject. So only impure pipewill run again and change its output. There will be no change in pure pipeoutput because it has not run again due to impure change inobject.: Change the text box values as follows.Company Name : ABCD LTD1111Location: Varanasi1111Now click onbutton. Output ofpipe will be as follows.And output ofpipe will be as follows.Let us understand what is happening. When we click onbutton thenwill execute and performs pure change inobject. So this time pure and impure pipe both will run again. It meansandboth pipe will run again and change its output.To run the application, find the steps.Download source code using download link given below on this page.Use downloadedin your Angular CLI application. To install Angular CLI, find the link Runusing command prompt.Access the URLFind the print screen of the output.I am done now. Happy angular learning!