Although Angular gives many build-in pipes, but in some case, we might need a custom pipe. Custom Pipes are function we define in angular for customize functions.

In this article. we will learn how to create a custom pipe in Angular.

There are two ways to create custom pipes, use Angular Cli or manual. I am using Angular Cli which is recommended in most of the cases. This is generate a class in app and also update in app.module.ts.


CustomPipe Cli

To install custom pipe using cli, type following command in terminal. This will generate custom pipe.

ng generate pipe custom

After this, we will see two new files in app directory. These are

  1. custom.pipe.spec.ts
  2. custom.pipe.ts

Also Angular will update CustomPipe in app.module.ts file.

custom.pipe.ts

        <!-- custom.pipe.ts -->

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

@Pipe({
    name: 'custom',
    standalone:true
})

export class CustomPipe implements PipeTransform {
    
transform(value: unknown, ...args: unknown[]): unknown {
    return null;
} 
}        

Custom Pipe Example

Lets create a custom pipe to convert first letter to uppercase for a string. We have some names in class component, but we want to print names with First Letter Capital.

Create a function in class CustomPipe and use in pipe.

Custom Function in Pipe

Angular

        <!-- app.component.html -->
    
<p>{{ 'angular' | custom}}</p>
        <!-- custom.pipe.ts -->

import { Pipe, PipeTransform } from '@angular/core';
    
@Pipe({
    name: 'custom',
    standalone:true
})
    
export class CustomPipe implements PipeTransform {
        
transform(x: string): string {
    return x.charAt(0).toUpperCase() + x.substr(1).toLowerCase();
} 
}