Back to course

Creating Custom Pipes

The Complete Angular Developer: From Zero to Hero

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

  1. Generate: Use the CLI: ng generate pipe status-label (or ng g p status-label).
  2. Implement PipeTransform: The generated pipe class must implement the PipeTransform interface and the transform method.
  3. Define Logic: Implement your transformation logic within the transform method.

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.