How to create a pipe in Angular?

In Angular, you can create a custom pipe by following these steps:

  1. Create a new file with a .pipe.ts extension in your project, for example my-filter.pipe.ts.
  2. Import the Pipe and PipeTransform interfaces from the @angular/core package:
import { Pipe, PipeTransform } from '@angular/core';
  1. Create a new class that implements the PipeTransform interface and decorate it with the @Pipe decorator:
@Pipe({
  name: 'myFilter'
})
export class MyFilterPipe implements PipeTransform {
  ...
}
  1. Implement the transform method in your class:
transform(value: any, ...args: any[]): any {
  ...
}
  1. Write the logic for your pipe in the transform method. This method takes a value and an array of arguments, and it should return the transformed value. For example, here’s a simple pipe that filters an array of items based on a search term:
transform(items: any[], searchText: string): any[] {
  if (!items) {
    return [];
  }
  if (!searchText) {
    return items;
  }
  searchText = searchText.toLowerCase();
  return items.filter(it => {
    return it.toLowerCase().includes(searchText);
  });
}
  1. Finally, declare your custom pipe in the declarations array of your module file:
@NgModule({
  declarations: [MyFilterPipe],
  ...
})
export class AppModule { }

With these steps, you can create a custom pipe in Angular. You can now use your custom pipe in your templates by using the pipe’s name in the template expression, for example:

<p *ngFor="let item of items | myFilter:searchText">{{ item }}</p>