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

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

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


Install Custom Pipe

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

ng generate pipe custom

or

ng g p 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 (non standalone applications).

custom.pipe.ts

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

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

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

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

Custom Pipe Example

Lets create a custom pipe to reverse a string. We have some names in class component, but we want to print names in reverse.

Create a function in class CustomPipe and use in pipe.

Custom Function in Pipe

ralugna

        <!-- 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.split('').reverse().join('');
} 
}        

Sort JSON Data

To Sort ann Array of objects, use following custom pipe


<table>
@for (i of cars | sort : 'price' : true; track $index ){
  <tr><td>{{i.name}}</td><td>{{i.type}}</td><td>{{i.price}}</td></tr>
}
</table>

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

@Pipe({
  name: 'sort'
})
export class SortPipe implements PipeTransform {

  transform(array: any[], field: string, order: boolean = true): any[] {
    if (!Array.isArray(array) || !field) return array;

    return array.sort((a, b) => {
      const valA = a[field];
      const valB = b[field];

      if (valA < valB) return order === true ? -1 : 1;
      if (valA > valB) return order === true ? -1 : 1;
      return 0;
    });
  }
}