Pipes in Angular are powerful tools that transform data for display in your templates.
Built-in Pipes in Angular
Angular provides several built-in pipes for common data transformations:
1. String Transformation Pipes
uppercase: Converts text to upper caselowercase: Converts text to lower casetitlecase: Capitalizes the first letter of each word
2. Number Transformation Pipes
number: Formats numberspercent: Formats numbers as percentagescurrency: Formats numbers as currency values
3. Date Transformation Pipe
date: Formats dates according to specified patterns
4. Object Transformation Pipes
json: Converts object to JSON stringslice: Selects a subset of an arraykeyvalue: Transforms object or map into an array of key-value pairs
Using Built-in Pipes
<!-- Date pipe -->
<p>Today is {{ today | date:'fullDate' }}</p>
<!-- Currency pipe -->
<p>Price: {{ price | currency:'USD' }}</p>
<!-- Chaining multiple pipes -->
<p>{{ name | lowercase | titlecase }}</p>
<!-- Pipe with parameters -->
<p>{{ amount | number:'1.2-2' }}</p>
Creating Custom Pipes
Simple Text Transformation Pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'initials'
})
export class InitialsPipe implements PipeTransform {
transform(value: string): string {
if (!value) return '';
return value
.split(' ')
.map(word => word.charAt(0).toUpperCase())
.join('');
}
}
Usage:
<p>Posted {{ postDate | timeAgo }}</p>
Registering Custom Pipes
Don’t forget to declare your pipes in your Angular module:
@NgModule({
declarations: [
InitialsPipe,
FilterPipe,
TimeAgoPipe,
FilterArrayPipe
],
// ... other module properties
})
export class AppModule { }