Back to all posts

Pipes in Angular


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 case
  • lowercase: Converts text to lower case
  • titlecase: Capitalizes the first letter of each word

2. Number Transformation Pipes

  • number: Formats numbers
  • percent: Formats numbers as percentages
  • currency: 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 string
  • slice: Selects a subset of an array
  • keyvalue: 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 { }