Welcome back! Today we’re exploring Angular Pipes – powerful tools for transforming data right in your templates while keeping your components clean. These are like filters that format your data before displaying it to users.
What Are Pipes?
Pipes are simple functions that:
- Accept input value and optional parameters
- Return transformed value
- Can be chained together
- Used with the pipe operator (
|
) in templates
html
{{ value | pipeName:param1:param2 }}
Built-in Pipes You Should Know
1. Text Transformation Pipes
typescript
message = 'angular pipes are awesome'; price = 19.99;
html
<!-- Uppercase/Lowercase --> <p>{{ message | uppercase }}</p> <!-- Output: ANGULAR PIPES ARE AWESOME --> <p>{{ message | titlecase }}</p> <!-- Output: Angular Pipes Are Awesome -->
2. Number Formatting
html
<!-- Decimal --> <p>{{ price | number:'1.2-2' }}</p> <!-- Output: 19.99 (1+ digits, 2 decimal places) --> <!-- Percent --> <p>{{ 0.75 | percent }}</p> <!-- Output: 75% --> <!-- Currency --> <p>{{ price | currency:'EUR':'symbol':'1.2-2' }}</p> <!-- Output: €19.99 -->
3. Date Formatting
typescript
today = new Date();
html
<!-- Default --> <p>{{ today | date }}</p> <!-- Output: Jun 15, 2023 --> <!-- Custom Format --> <p>{{ today | date:'fullDate' }}</p> <!-- Output: Thursday, June 15, 2023 --> <p>{{ today | date:'yyyy-MM-dd HH:mm' }}</p> <!-- Output: 2023-06-15 14:30 -->
4. Advanced Pipes
typescript
users = ['Alice', 'Bob', 'Charlie'];
html
<!-- Slice --> <p>{{ users | slice:1:3 }}</p> <!-- Output: Bob,Charlie --> <!-- KeyValue --> <div *ngFor="let item of {name: 'John', age: 30} | keyvalue"> {{ item.key }}: {{ item.value }} </div> <!-- JSON (great for debugging) --> <pre>{{ users | json }}</pre>
Creating Custom Pipes
Let’s build an excerpt
pipe that shortens text with ellipsis.
Step 1: Generate Pipe
bash
ng generate pipe excerpt # Shorthand: ng g p excerpt
Step 2: Implement Pipe Logic
typescript
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'excerpt' }) export class ExcerptPipe implements PipeTransform { transform(value: string, limit = 50, ellipsis = '...'): string { if (value.length <= limit) return value; return value.substring(0, limit) + ellipsis; } }
Step 3: Use Your Pipe
html
<p>{{ longText | excerpt:100:' ...' }}</p>
Advanced Pipe Techniques
1. Pure vs Impure Pipes
- Pure pipes (default): Only recompute when primitive input changes
- Impure pipes: Recompute on every change detection cycle
typescript
@Pipe({ name: 'filter', pure: false // Use with caution! })
2. Pipe Parameters
html
<!-- Multiple parameters --> <p>{{ value | pipeName:param1:param2 }}</p> <!-- Chaining pipes --> <p>{{ value | pipe1 | pipe2 }}</p>
3. Internationalization Pipes
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; registerLocaleData(localeFr);
html
<!-- French number formatting --> <p>{{ price | number:'1.2-2':'fr' }}</p> <!-- Output: 19,99 -->
Real-World Pipe Examples
- File Size Formatter:Â
1024 → "1 KB"
- Duration Formatter:Â
125 → "2m 5s"
- Search Filter: Filter array by search term
- Safe HTML: Sanitize HTML content (with DomSanitizer)
Performance Considerations
- Avoid complex operations in pipes
- For expensive operations, consider memoization
- Prefer pure pipes when possible
- Be cautious with impure pipes on large datasets
Hands-On Exercise
Create a initials
pipe that:
- Takes a full name (string)
- Returns initials (e.g., “John Doe” → “JD”)
- Handles single names (“Cher” → “C”)
- Optional parameter for maximum initials (default 2)
What’s Next?
In Part 7, we’ll dive into Angular Modules – the building blocks for organizing your application!