20. Creating Custom Pipes
While Angular offers many built-in pipes, you often need custom logic to transform data unique to your application requirements (e.g., converting a status code to a readable label, or calculating taxes).
Steps to Create a Custom Pipe
- Generate: Use the CLI:
ng generate pipe status-label(orng g p status-label). - Implement
PipeTransform: The generated pipe class must implement thePipeTransforminterface and thetransformmethod. - Define Logic: Implement your transformation logic within the
transformmethod.
Example: Status Label Pipe
This pipe converts a numeric status code into a readable text label.
typescript import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'statusLabel' // The name used in the template (pipe syntax) }) export class StatusLabelPipe implements PipeTransform {
transform(value: number, language: string = 'en'): string { switch (value) { case 1: return language === 'fr' ? 'Actif' : 'Active'; case 2: return language === 'fr' ? 'En attente' : 'Pending'; default: return 'Unknown Status'; } } }
Usage in Template
Component: currentStatus: number = 2;
html
Status (EN): {{ currentStatus | statusLabel }}
Status (FR): {{ currentStatus | statusLabel:'fr' }}
Note on Purity: By default, pipes are pure, meaning they only recalculate if the input value itself changes (primitive change) or if the object reference changes (object change). This is highly performant. If you need it to recalculate on every change detection cycle, you can set pure: false in the @Pipe decorator, but this is rarely recommended.