Custom Pipes: Build Your Own Formatter
Create a custom pipe for real-world formatting, like abbreviating large numbers.
Custom pipes let you create your own formatting logic, reusable across the app. ## Example goal: 1200 -> 1.2K ### Step 1: Create a pipe ```ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'shortNumber', standalone: true, }) export class ShortNumberPipe implements PipeTransform { transform(value: number): string { if (value >= 1_000_000) return (value / 1_000_000).toFixed(1) + 'M'; if (value >= 1_000) return (value / 1_000).toFixed(1) + 'K'; return String(value); } } ``` ### Step 2: Use it in a standalone component ```ts import { Component } from '@angular/core'; import { ShortNumberPipe } from './short-number.pipe'; @Component({ selector: 'app-stats', standalone: true, imports: [ShortNumberPipe], template: `<p>Views: {{ views | shortNumber }}</p>`, }) export class StatsComponent { views = 15230; } ``` Result: ``` Views: 15.2K ``` > Next: Components communication, passing data with @Input.