Custom Pipes
Sometimes the built-in pipes aren't enough. You need custom transformation logic. Angular lets you create your own custom pipes for any transformation you can imagine.
Create a pipe using the
@Pipe decorator and implement the PipeTransform interface.Example 1: A pipe that filters an array
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string, propertyName: string): any[] {
if (!items) return [];
if (!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter(item => {
return item[propertyName].toLowerCase().includes(searchText);
});
}
}
Usage in template:<input [(ngModel)]="searchTerm" placeholder="Search...">
<li *ngFor="let user of users | filter:searchTerm:'name'">{{ user.name }}</li>
Example 2: A pipe that formats phone numbers
@Pipe({
name: 'phone'
})
export class PhonePipe implements PipeTransform {
transform(phoneNumber: string): string {
if (!phoneNumber) return '';
// Remove non-digits
const cleaned = phoneNumber.replace(/D/g, '');
// Format as (XXX) XXX-XXXX
const match = cleaned.match(/^(d{3})(d{3})(d{4})$/);
if (match) {
return `(${match[1]}) ${match[2]}-${match[3]}`;
}
return phoneNumber;
}
}
Usage:<p>{{ '1234567890' | phone }}</p> <!-- (123) 456-7890 -->
Pure vs Impure Pipes
By default, pipes are pure – they only run when the input value changes. For pipes that need to run on every change detection (like a pipe that filters an array that might be mutated), set
pure: false:@Pipe({
name: 'impureFilter',
pure: false
})
Two Minute Drill
- Create custom pipes with @Pipe decorator and implement PipeTransform.
- The transform method receives the value and optional parameters.
- Use custom pipes in templates just like built-in pipes.
- Pipes are pure by default (only run when input changes).
- Use pure: false cautiously – can impact performance.
- Great for reusable data transformations.
Need more clarification?
Drop us an email at career@quipoinfotech.com
