Step by Step creating Custom Pipe in Angular

Read full article on the Infragistics blog

Angular pipes take data as input and transform it to your desired output. For example, using interpolation you are displaying name of the product. Now you want the product name always displayed in the uppercase. You can do this using Angular pipe uppercase.


import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `{{productName | uppercase}}`
})
export class AppComponent {
productName = 'Cricket Bat';
}

view raw

custompipe1.js

hosted with ❤ by GitHub

In above component, productName will be displayed in uppercase. Therefore, pipe takes an input and transforms it into desired output as shown below:

Angular library provides us many built-in pipes like

  • UpperCasePipe
  • LowerCasePipe
  • CurrencyPipe
  • PercentPipe
  • DatePipe etc.

Let us see how we could use the built-in currency pipe.


import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `{{productName | uppercase}} = {{productPrice | currency}}`
})
export class AppComponent {
productName = 'Cricket Bat';
productPrice = 990;
}

view raw

custompipe2.js

hosted with ❤ by GitHub

You can also pass parameters to a pipe using the colon. You can pass input to currency pipe as shown below:


import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `{{productName | uppercase}} = {{productPrice | currency:'CAD':'symbol-narrow':'4.2-2'}}`
})
export class AppComponent {
productName = 'Cricket Bat';
productPrice = 990;
}

view raw

custompipe3.js

hosted with ❤ by GitHub

Even though Angular provides many default pipes, there could be requirements when you create custom pipes. Creating a custom pipe is very as simple as creating a function.  Let us say that we want to create a pipe, which will capitalize first letter of each words in a string.

Consider below component,


import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<ul *ngFor='let n of names'>
<li>{{n.name}}</li>
</ul>
`
})
export class AppComponent {
names = [];
constructor() {
this.names = this.getNames();
}
getNames() {
return [
{ 'name': 'dhananjay Kumar' },
{ 'name': 'jason beres' },
{ 'name': 'adam jafe' }
];
}
}

view raw

custompipe5.js

hosted with ❤ by GitHub

This component will print names as below:

Now we want to capitalize the first letter of each word in the name. To do that we need to write a custom pipe.  To create a pipe, you need to follow these steps:

Read full article on the Infragistics blog

Leave a comment

Create a website or blog at WordPress.com