In Angular, you can create a custom pipe by following these steps:
- Create a new file with a
.pipe.ts
extension in your project, for examplemy-filter.pipe.ts
. - Import the
Pipe
andPipeTransform
interfaces from the@angular/core
package:
import { Pipe, PipeTransform } from '@angular/core';
- Create a new class that implements the
PipeTransform
interface and decorate it with the@Pipe
decorator:
@Pipe({
name: 'myFilter'
})
export class MyFilterPipe implements PipeTransform {
...
}
- Implement the
transform
method in your class:
transform(value: any, ...args: any[]): any {
...
}
- 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);
});
}
- 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>