Directives & Pipes
Pipes
Template Mein Data Transform Karna
💡 Pipe ek water filter jaisa hai — raw data (paani) andar jaata hai, EK direction mein "pipe" (|) se guzarकर, clean/formatted data (filtered paani) bahar aata hai — template mein hi data ko display-ready banane ka clean tareeka.
Pipe (| symbol) template mein DATA ko TRANSFORM karta hai, bina component logic change kiye. Built-in pipes: date (date formatting), currency, uppercase/lowercase, json (debugging ke liye), async (Observables/Promises ke liye — RxJS category mein detail).
// <p>{{ today | date:'fullDate' }}</p>
// <p>{{ price | currency:'INR' }}</p>
// <p>{{ name | uppercase }}</p>
// <p>{{ user | json }}</p> — debugging ke liye poora object dikhाना
// Multiple pipes chain kar sakte ho:
// <p>{{ name | lowercase | titlecase }}</p>
// Parameters ke saath:
// <p>{{ birthDate | date:'dd/MM/yyyy' }}</p>🚰
Pipe ek water filter jaisa hai — raw data (paani) andar jaata hai, EK direction mein "pipe" (|) se guzarकर, clean/formatted data (filtered paani) bahar aata hai — template mein hi data ko display-ready banane ka clean tareeka.
1 / 6
⚡ Quick Recap
- | (pipe symbol) = data ko template mein transform karo
- Built-in: date, currency, uppercase, json, async
- Chainable — multiple pipes ek saath, left-to-right
On this page (2 subtopics)
Pure pipes (DEFAULT) sirf tab RE-RUN hote hain jab input VALUE change hoti hai (reference equality check) — fast, efficient. Impure pipes (pure: false) HAR change detection cycle mein re-run hote hain — slower, lekin zaroori jab array/object CONTENT change ho bina reference badle.
@Pipe({
name: 'customFilter',
pure: false // impure — har change detection cycle mein chalega
})
export class CustomFilterPipe implements PipeTransform {
transform(items: any[], filterText: string): any[] {
return items.filter(item => item.name.includes(filterText));
}
}Common Mistake: Impure pipes PERFORMANCE HEAVY hain — har change detection cycle (jo bahut baar chalता hai) mein re-execute hote hain. Sparingly use karo, aur jab possible ho, pure pipes ya component logic prefer karo.
@Pipe decorator se custom pipe banate hain — PipeTransform interface implement karo, transform() method mein actual logic likho.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
transform(value: string, limit: number = 50): string {
if (value.length <= limit) return value;
return value.substring(0, limit) + '...';
}
}
// Use: <p>{{ longText | truncate:100 }}</p>Tip: Custom pipes reusable, testable transformation logic ke liye perfect hain — jo bhi text/data-formatting logic multiple templates mein repeat ho raha ho, ek pipe mein extract kar do.