Angular Pipes & Formatting

In any web application, raw data fetched from a database rarely looks pretty. A date might arrive as "2023-10-15T08:30:00Z" and a price might arrive as 1499.5.Angular Pipes are simple functions you use directly inside HTML templates to transform that raw data into a beautiful format for the user.

Built-in Angular Pipes

You utilize a Pipe by using the vertical bar symbol ( | ) inside your interpolation brackets. Angular comes with several highly useful pipes out of the box.

1. The DatePipe

// .ts
birthday = new Date(1995, 3, 15);

// .html
<p>Default: {{ birthday | date }}</p>            <!-- Apr 15, 1995 -->
<p>Short: {{ birthday | date:'short' }}</p>      <!-- 4/15/95, 12:00 AM -->
<p>Custom: {{ birthday | date:'MMMM d, y' }}</p> <!-- April 15, 1995 -->

2. The CurrencyPipe & DecimalPipe

// .ts
price: number = 42.5;

// .html
<p>US Dollars: {{ price | currency:'USD' }}</p> <!-- $42.50 -->
<p>Euro: {{ price | currency:'EUR':'symbol' }}</p> <!-- €42.50 -->

<p>Decimals: {{ 3.14159265 | number:'1.1-2' }}</p> <!-- 3.14 -->

3. Uppercase, Lowercase, and Titlecase

<p>{{ 'hello world' | uppercase }}</p> <!-- HELLO WORLD -->
<p>{{ 'hELlo WoRLD' | titlecase }}</p> <!-- Hello World -->

4. The JsonPipe

Incredibly useful for debugging! You can dump an entire TypeScript object directly to the screen to inspect it.

<pre>{{ complexObjectData | json }}</pre>

Chaining Pipes

You can apply multiple pipes simultaneously by separating them with another vertical bar.

<p> {{ birthday | date:'fullDate' | uppercase }} </p>

Creating Custom Pipes

If the built-in pipes aren't enough, you can generate your own using ng g pipe my-custom. This creates a class implementing the PipeTransform interface.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'truncate', standalone: true })
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit: number = 20): string {
    if (!value) return '';
    return value.length > limit ? value.substring(0, limit) + '...' : value;
  }
}

Usage: {{ 'A very incredibly long string' | truncate:10 }} Outputs: A very inc...

Conclusion

Pipes keep your TypeScript Component logic extremely clean because you no longer need functions like formatDate() polluting your typescript class. Next, we explore the backbone of Angular architecture: Services and Dependency Injection.