Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to create a custom pipe in AngularJS ?

  • Last Updated : 11 Sep, 2021

In this article, we will learn how to generate custom pipe other than using built-in pipe in Angular & also explore its implementation. The Pipe is a function that is used to modify the data before rendering it to the user. Some of the pre-built pipes are date, uppercase, lowercase, currency, decimal, number etc. Angular has a powerful feature named Data binding which helps us to bind the class property to the HTML element property. Sometimes, we need to display properly formatted data before we display it to the user. For instance, if we need to print the date then it might happen that a long format of date will be printed that may be irrelevant to the user. For this reason, pipes are used to transforming the data before the data is displayed on the browser. We can change property values using pipes to make them more user-friendly or appropriate for the specific area. We can assume pipes as functions that can take parameters, perform computations and return something. Pipes take strings, integers, dates and arrays as an input value separated by ‘|’ followed by the pipe name and returns the formatted result. Parameters are defined by including a colon and the value of the parameter. In order to save the file, we need to save it as <fileName>.pipe.ts. The syntax for displaying the transformed value using a pipe in component template expression is as follows:

Syntax:

{{ inputValue | pipename : parameter }}

However, we might come to a situation where we want to add more complex functionality in the data transformation. For this reason, Angular provides custom pipes. Custom pipes can be used for various use cases like formatting the phone number, highlighting the search result keyword, returning the square of a number, etc. For generating the custom pipes, we can follow 2 ways:

  • By creating a separate file for pipe, we have to manually set up & configure the pipe function with the component file & need to import it into the module file.
  • By using Angular CLI, it will set up all the necessary configurations in the component & module files automatically.

We will understand both approaches through examples in a sequence.

 



Method 1: Let’s follow the steps to generate the custom pipes manually:

Step 1: Construct a class that implements the PipeTransform interface. Ensure to export the class so that other components can use it to import the pipe. Use UpperCamelCase to write the name of the pipe class. In this example, we have named the class as ArbitraryPipe

export class ArbitraryPipe implements PipeTransform {}

Step 2: The PipeTransform interface has a transform method. In the transform method, we write code to transform and return a value. In this case, we want to pass in the character that we want to replace with spaces. The method return type is also defined as a string because we are returning the transformed string.

export class ArbitraryPipe implements PipeTransform {
  transform(value: string, character: string): string {
    return value.replace(character, ' ');
  }
}

Step 3: To make the class a pipe, add a pipe decorator to it. This is a function, so we add parentheses like the other decorators. The name of the pipe is specified in an object passed to the function. The name of the pipe will be used in the template.

@Pipe({
  name: 'arbitrary'
})
export class ArbitraryPipe implements PipeTransform {
  transform(value: string, character: string): string {
    return value.replace(character, ' ');
  }
}

Step 4: Import pipe and pipeTransform from @angular/core so that we can use the pipe decorator and pipeTransform interface from those modules respectively. 

arbitrary.pipe.ts




import { Pipe, PipeTransform } from '@angular/core';
  
@Pipe({
  name: 'arbitrary'
})
export class ArbitraryPipe implements PipeTransform {
  transform(value: string, character: string): string {
    return value.replace(character, ' ');
  }
}

Step 5: Let’s now use our arbitrary pipe in the component template. Simply, add a pipe and the pipe name to a template to use the arbitrary pipe. Use colons to separate any arguments that the transformation requires. The first argument to the transform method is the value to be converted, which in this case is our productCode. This is our pipe name. The colon denotes a pipe parameter, therefore our dash is provided as the transform method’s second argument. The passed-in value is then transformed as per the method’s logic, and the altered string is returned and displayed.

 



app.component.html




<h2>Product code without using custom pipe is {{productCode}} </h2>
  
<h2>Product code using custom pipe is {{productCode | arbitrary:'-'}} </h2>

Step 6: In this case, we need to import the ArbitraryPipe in the module file, also add our arbitrary pipe to the declaration array of @NgModule in the app.module.ts file to declare it in AppModule.

app.module.ts




import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { ArbitraryPipe } from './arbitrary.pipe';
  
@NgModule({
  declarations: [AppComponent, ArbitraryPipe],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Our app.component.ts file looks like below:

app.component.ts




import { Component } from '@angular/core';
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {
  productCode = '200-300';

Output: 

Method 2: In this case, we will use Angular CLI to generate the pipe & Angular CLI will take care of all the configuration setup that we have performed in the 1st method ie., it will automatically import random pipe & include it in the declaration array, also configure the random.pipe.ts file. To generate the pipe, we follow the below command: 

ng generate pipe random

This command will generate a file called random.pipe.ts that contains sample code for implementing custom pipe at the application root level. It will also build a spec file for writing unit tests and modify the reference in app.module.ts.

 



random.pipe.ts




import { Pipe, PipeTransform } from '@angular/core';
  
@Pipe({
  name: 'random'
})
export class RandomPipe implements PipeTransform {
  transform(value: string, character: string): string {
    return value.replace(character, ': ');
  }
}

Our app.component.ts file looks like below:

app.component.ts




import { Component } from '@angular/core';
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'GeeksforGeeks -  a computer science portal for geeks ';
}

We can use the pipe declaration in the HTML template.

app.component.html




<h4>Without using custom pipe: </h4>
<h2>{{name}}</h2>
<h4>With using custom pipe:</h4>
<h2>{{name | random: '-'}}</h2>

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 { RandomPipe } from './random.pipe';
  
@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, RandomPipe],
  bootstrap: [AppComponent]
})
export class AppModule {}

Output: After running the ng serve command, the below output will be displayed.




My Personal Notes arrow_drop_up
Recommended Articles
Page :