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.
- import {
- Pipe,
- PipeTransform
- } from '@angular/core';
- @Pipe({
- name: 'name of pipe used in markup'
- })
- export class NameofClass implements PipeTransform {
- transform(value: string, args: string[]): any {
-
- return value;
- }
- }
-
-
-
- if ('this_is' == /an_example/) {
- of_beautifier();
- } else {
- var a = b ? (c % d) : e[f];
- }
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
- import {
- Pipe,
- PipeTransform
- } from '@angular/core';
- @Pipe({
- name: 'titlecase'
- })
- export class TitleCasePipe implements PipeTransform {
- transform(value: string, args: string[]): any {
- if (!value) return value;
- return value.replace(/\w\S*/g, function(txt) {
- return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
- });
- }
- }
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 - import {
- Component
- } from '@angular/core';
-
- import {
- TitleCasePipe
- } from './titlecasepipe';
- @Component({
- selector: 'test-app',
- pipes: [TitleCasePipe],
- templateUrl: './app/example.html'
- })
- export class AppComponent {
- name = "jigneshtrivedi";
- }
example.html - <div>
- <h4>Title Case Pipe example</h4>
- Hello, My name is {{name | titlecase}}
- </div>
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
- import {
- Pipe,
- PipeTransform
- } from '@angular/core';
- @Pipe({
- name: 'bold'
- })
- export class BoldPipe implements PipeTransform {
- transform(value: string): any {
- return '<b>' + value + '</b>';
- }
- }
app.component.ts - import {
- Component
- } from '@angular/core';
-
- import {
- BoldPipe
- } from './textboldpipe';
- @Component({
- selector: 'test-app',
- pipes: [BoldPipe],
- templateUrl: './app/example.html'
- })
- export class AppComponent {
- name = "jigneshtrivedi";
- myText = "This is my test string.";
- }
example.html - <div>
- <h4>Bold Pipe example</h4>
- Hello, My name is <span [outerHTML]="name | titlecase | bold"></span>
- </div>
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 - import {
- Pipe,
- PipeTransform
- } from '@angular/core';
- @Pipe({
- name: 'limitword'
- })
- export class LimitWordPipe implements PipeTransform {
- transform(value: string, limit: string, trail: string): any {
- letlimitChar = limit != null ? parseInt(limit) : 10;
- lettrailString = (trail != null) ? trail : '...';
- returnvalue.length > limitChar ? value.substring(0, limitChar) + trailString : value;
- }
- }
- app.component.ts
- import {
- Component
- } from '@angular/core';
-
- import {
- LimitWordPipe
- } from './limitwordpipe';
- @Component({
- selector: 'test-app',
- pipes: [LimitWordPipe],
- templateUrl: './app/example.html'
- })
- export class AppComponent {
- name = "jigneshtrivedi";
- myText = "This is my test string.";
- }
- example.html <
- div >
- <
- h4 > Limit word Pipe example < /h4>
- 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 / >
- <
- /div>
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
- import {
- NgModule
- } from '@angular/core';
- import {
- BrowserModule
- } from '@angular/platform-browser';
- import {
- FormsModule
- } from '@angular/forms';
- import {
- AppComponent
- } from './app.component';
-
- import {
- TitleCasePipe
- } from './titlecasepipe';
- import {
- BoldPipe
- } from './textboldpipe';
- import {
- LimitWordPipe
- } from './limitwordpipe';
- @NgModule({
- imports: [BrowserModule, FormsModule],
- declarations: [AppComponent, TitleCasePipe, BoldPipe, LimitWordPipe],
- bootstrap: [AppComponent],
- })
- export class AppModule {}
App.component.ts - import {
- Component
- } from '@angular/core';
- @Component({
- selector: 'test-app',
- templateUrl: './app/example.html'
- })
- export class AppComponent {
- name = "jigneshtrivedi";
- myText = "This is my test string.";
- }
Example.html - <h4>Custom pipes in Angular 2 </h4>
- <div>
- <h4>Title Case Pipe example</h4>
- Hello, My name is {{name | titlecase}}
- </div>
- <br/>
- <div>
- <h4>Bold Pipe example</h4>
- Hello, My name is <span [outerHTML]="name | titlecase | bold"></span>
- </div>
- <div>
- <h4>Limit word Pipe example</h4>
- 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/>
- </div>
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.