How would you create a custom pipe in Angular, such as one that truncates long text?
Short answer
You create a class decorated with the Pipe decorator, specifying a name to use in templates, and implement a transform method that receives the input value and any arguments, returning the transformed result.
Advertisement
AModel answer
You create a class decorated with the Pipe decorator, specifying a name to use in templates, and implement a transform method that receives the input value and any arguments, returning the transformed result.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate', standalone: true })
export class TruncatePipe implements PipeTransform {
transform(value: string, limit: number = 50): string {
return value.length > limit ? value.substring(0, limit) + '...' : value;
}
}
// Used as: <p>{{ description | truncate:100 }}</p>Real-world example
A blog listing page shows a shortened preview of each article's content using a custom truncate pipe, keeping the layout clean and consistent regardless of how long the original article text actually is.
Likely follow-ups
- How do you pass multiple arguments to a custom pipe?
- What naming convention should a custom pipe follow to avoid conflicting with built in pipes?
Related topics