Custom Pipes in Angular
Let's look at how to create custom pipes in Angular — a powerful way to transform data your way when built-in pipes don't cut it.
🔧 When to Create a Custom Pipe?
Use a custom pipe when:
- You want reusable transformations.
- Built-in pipes don't cover your use case.
- You want clean templates (instead of complex method calls).
✅ Steps to Create a Custom Pipe
1. Generate a Pipe
Use Angular CLI:
ng generate pipe myCustom
This creates two files:
my-custom.pipe.tsmy-custom.pipe.spec.ts(for testing)
2. Basic Pipe Example: Reverse a String
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
3. Use in Template
<p>{{ 'angular' | reverse }}</p> <!-- ralu gna -->
4. Using Pipe with Parameters
Let's create a pipe to truncate text after a certain number of characters.
@Pipe({
name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit: number = 10, trail: string = '...'): string {
return value.length > limit ? value.substring(0, limit) + trail : value;
}
}
Usage:
<p>{{ 'This is a long sentence' | truncate:10 }}</p> <!-- This is a ... -->
🔐 Don't Forget to Declare It
Add your pipe to the declarations array in the relevant Angular module:
@NgModule({
declarations: [
AppComponent,
ReversePipe,
TruncatePipe
]
})
export class AppModule {}
Want to explore Pure vs Impure Pipes next, or dive into Services & Dependency Injection?
Comments
Post a Comment