Angular Custom Pipe

Creating Angular Custom Pipe

In this article, I am going to discuss how to create Angular Custom Pipe with an example. Please read our previous article before proceeding to this article where we discussed the Built-in Angular Pipes. At the end of this article, you will understand how to create custom pipe and when do we need to create custom pipes and how to use it in Angular Application.

Let us understand the need of Angular Custom Pipe with an example.

Suppose you want to display the students detail in a web page. So, let us first create the student data in the AppComponent.

Modify app.component.ts file:

Open app.component.ts file and then copy and paste the following code in it. As you can here we simply created an student array.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    students: any[] = [
        {
            ID: 'std101', Name: 'Rakesh Rout',
            DOB: '12/8/1988', Gender: 'Male', CourseFee: 1234.56
        },
        {
            ID: 'std102', Name: 'Anurag Mohanty', 
            DOB: '10/14/1989', Gender: 'Male', CourseFee: 6666.00
        },
        {
            ID: 'std103', Name: 'Priyanka Dewangan', 
            DOB: '7/24/1992', Gender: 'Female', CourseFee: 6543.15
        },
        {
            ID: 'std104', Name: 'Hina Sharma', 
            DOB: '8/19/1990', Gender: 'Female', CourseFee: 9000.50
        },
        {
            ID: 'std105', Name: 'Sambit Satapathy',
            DOB: '4/12/1991', Gender: 'Male', CourseFee: 9876.54
        }
    ];
}

Let us show these student data in the web page.

Modify app.student.html file:

Open app.student.html file and then copy and paste the following code in it. As you can here we have applied some built-in pipes to format the data.

<table border="1">
    <thead>
        <tr>
            <th>Student ID</th>
            <th>Name</th>
            <th>DOB</th>
            <th>Gender</th>
            <th>CourseFee</th>            
        </tr>
    </thead>
    <tbody>
        <tr *ngFor='let student of students'>
            <td>{{student.ID | uppercase}}</td>
            <td>{{student.Name }}</td>
            <td>{{student.DOB | date:'dd/MM/yyyy'}}</td>
            <td>{{student.Gender | lowercase}}</td>
            <td>{{student.CourseFee | currency:'USD':true}}</td>
        </tr>
    </tbody>
</table>

At this moment if you run the application, then you will get the following output in the browser.

Creating Angular Custom Pipe

Now, the requirement changes, now they want to show the title depending on the gender of the student I.e. we need to add Mr. or Miss. prefixed before the name of the student as shown in the below image.

when do we need to create custom pipes in angular

How we can achieve this?

We can achieve this very easily by creating an angular custom pipe.

How to create Angular Custom Pipe?

In order to create a custom pipe in angular, you have to apply the @Pipe decorator to a class which you can import from the Angular Core Library. The @Pipe decorator allows you to define the pipe name that you will use within the template expressions. The syntax to create a pipe in angular is given below.

How to create Angular Custom Pipe?

Note: The transform method will decide the input types, the number of parameters and the output type.

Creating Angular Custom Pipe using Angular CLI:

Let say we want to create a custom pipe with the name MyTitle. In order to create a custom MyTitle pipe open a new terminal and type ng g pipe MyTitle –flat and press enter as shown in the below image.

Creating Angular Custom Pipe using Angular CLI

Once you type ng g pipe MyTitle –flat and press enter, it will take some time and create two files (my-title.pipe.ts and my-title.pipe.spec.ts) within the app folder. Along the way, it also update the app.module.ts file.

Modify my-title.pipe.ts file:

Now, open my-title.pipe.ts file and then copy and paste the following code in it.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'myTitle'
})
export class MyTitlePipe implements PipeTransform {

  transform(name: string, gender: string): string {
    if (gender.toLowerCase() == "male")
        return "Mr. " + name;
    else
        return "Miss. " + name;
  }

}
Understanding above code:
  1. First, we import the Pipe decorator and PipeTransform interface from the Angular core Library.
  2. Then we decorated the “MyTitlePipe” class with the Pipe decorator so that this class will become an Angular pipe.
  3. We then set the name property of the pipe decorator to myTitle so that we can use this name (myTitle) on any HTML page where we want this pipe functionality.
  4. The MyTitlePipe class implements the PipeTransform interface and that interface has one method called transform() and here we implement that method.
  5. As you can see in the above code, the transform method takes 2 parameters (name and gender). The name parameter will receive the name of the student whereas the gender parameter will receive the gender of the student. The method returns a string i.e. Mr. or Miss. prefixed to the name of the student depending on their gender.
Registering the Custom Pipe in Angular Application:

Before using the custom MyTitlePipe, first we need to register it in the app.module.ts file. If you are creating it using Angular CLI, then the angular framework will automatically register the pipe. To make sure, let us modify the app.module.ts file as shown below. Here, first we need to import the MyTitlePipe and then we need to include it in the “declarations” array of NgModule decorator.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MyTitlePipe } from './my-title.pipe';

@NgModule({
  declarations: [
    AppComponent,
    MyTitlePipe,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Using the Custom Pipe in Angular Application:

Modify the app.component.html file as shown below. Notice that we are passing the student gender as an argument for the gender parameter to our custom pipe. The Student name gets passed automatically.

<table border="1">
    <thead>
        <tr>
            <th>Student ID</th>
            <th>Name</th>
            <th>DOB</th>
            <th>Gender</th>
            <th>CourseFee</th>            
        </tr>
    </thead>
    <tbody>
        <tr *ngFor='let student of students'>
            <td>{{student.ID | uppercase}}</td>
            <td>{{student.Name | myTitle:student.Gender}}</td>
            <td>{{student.DOB | date:'dd/MM/yyyy'}}</td>
            <td>{{student.Gender | lowercase}}</td>
            <td>{{student.CourseFee | currency:'USD':true}}</td>
        </tr>
    </tbody>
</table>

With the above changes in place, now run the application and you should the output as expected.

In the next article, I am going to discuss Angular Routing in detail. Here, in this article, I try to explain how to create Angular Custom Pipe with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

6 thoughts on “Angular Custom Pipe”

  1. Waiting for next tutorial on angular. Will be better if you make a complete asp.net crud with angular at the end.

    Thanks a lot for the hard work. Keep it up guys.

    *** Everyone please keep social distance to protect your loved ones from CORONA ***

    1. They mentioned above the coding , The Student name gets passed automatically. But I don’t know how it passed the argument automatically.

    1. In pipe concept, on which property, we need formation, we need to use that property then the pipe symbol like:

      property | pipename
      => this syntax style tells the Angular that put the specific pipe on that property and basically it will be assigned to the 1st parameter of the transform method

      then if the transform method has any parameter, we need to pass them with the syntax style using :

      property | pipename : parameter1 : parameter2

  2. In the HTML template, {{student.Name | myTitle:student.Gender}} passes the student’s name and gender to the custom pipe myTitle. The pipe then transforms the name based on the gender and returns the modified name

Leave a Reply

Your email address will not be published. Required fields are marked *