Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 74 ยท Templates and Data Binding

Pipes

Learn Angular pipes - date, currency, number, percent, json, async, slice, keyvalue, chaining, pure versus impure pipes and how to write a custom PipeTransform.

Your data rarely arrives in the form people want to read. A price is the number 1234.5, a date is a timestamp, a percentage is 0.256. You could format everything in the component class, but formatting is a concern of the template: how a value is displayed, not what it is. Angular's answer is the pipe: a small function you apply inside a template with the vertical bar, like {{ price | currency }}.

This lesson covers the built-in pipes you will use every day, how to pass arguments and chain pipes, the difference between pure and impure pipes (the most common source of surprises), and how to write your own. It builds on interpolation and template expressions.

Angular's compiler is not available on this site, so the Angular snippets are read-only. The runnable <TryIt> examples are stand-ins in plain TypeScript: a tiny pipe registry that mimics several built-in pipes with the browser's Intl formatters, and a demonstration of pure versus impure behavior. The exact output of real Angular pipes depends on the app's locale and Angular version.

Using pipes

A pipe takes the value on its left and returns a transformed value. Arguments come after a colon:

HTML
<p>{{ today | date }}</p>
<p>{{ today | date: 'mediumDate' }}</p>
<p>{{ price() | currency: 'USD' }}</p>
<p>{{ ratio() | percent }}</p>
<p>{{ total() | number: '1.2-2' }}</p>

A standalone component must import each pipe it uses. Pipes such as DatePipe, CurrencyPipe, DecimalPipe (the number pipe), PercentPipe, JsonPipe, AsyncPipe, SlicePipe, KeyValuePipe, UpperCasePipe, LowerCasePipe and TitleCasePipe come from @angular/common:

TypeScript
import { Component, signal } from '@angular/core';
import { CurrencyPipe, DatePipe, PercentPipe } from '@angular/common';

@Component({
  selector: 'app-invoice',
  imports: [CurrencyPipe, DatePipe, PercentPipe],
  template: `
    <p>Issued {{ issued | date: 'mediumDate' }}</p>
    <p>Total {{ total() | currency: 'USD' }}</p>
    <p>Tax rate {{ taxRate | percent }}</p>
  `,
})
export class InvoiceComponent {
  issued = new Date(2024, 5, 15);
  total = signal(1234.5);
  taxRate = 0.2;
}

With the default en-US locale, that template prints Jun 15, 2024, $1,234.50 and 20%.

The built-in pipes you will use

Pipe What it does Example
date Formats a Date, timestamp or ISO string; takes a format name or pattern, and optionally a time zone {{ d | date: 'shortDate' }}
currency Currency symbol, separators and two decimals by default {{ p | currency: 'EUR' }}
number Digits and separators; the argument is minInt.minFrac-maxFrac {{ n | number: '1.0-2' }}
percent Multiplies by 100 and adds % {{ 0.256 | percent }} shows 26%
json JSON.stringify with indentation, for debugging {{ obj | json }}
slice Array.prototype.slice semantics for arrays and strings {{ items | slice: 0 : 3 }}
keyvalue Turns an object or Map into an array of { key, value }, sorted by key by default @for (kv of obj | keyvalue; track kv.key)
uppercase, lowercase, titlecase Change letter case {{ name | titlecase }}
async Subscribes to an Observable or Promise and unwraps the latest value {{ data$ | async }}

(The backslashes before the vertical bars in the table are only there so the table renders; in a template you write a plain |.)

json is the best debugging friend you have: <pre>{{ form.value | json }}</pre> shows the exact state of an object while you build. keyvalue lets @for loop over an object, which it otherwise cannot do. And the async pipe subscribes when the view is created, unsubscribes when it is destroyed and marks the view for update on each new value, so you never write the cleanup yourself. For signals you need no pipe at all: you simply call the signal, {{ count() }}. Observables get their own chapter later (RxJS Essentials: Observables).

Chaining and precedence

Pipes chain left to right; the output of one is the input of the next:

HTML
<p>{{ title | slice: 0 : 20 | uppercase }}</p>
<p>{{ createdAt | date: 'MMM d' | lowercase }}</p>

One trap: the pipe operator has higher precedence than the ternary operator, so in {{ flag ? a : b | uppercase }} the pipe applies to b only. Add parentheses to be explicit: {{ (flag ? a : b) | uppercase }}.

Arguments can be any expression, including signals: {{ value() | number: digits() }}.

A runnable stand-in: a pipe pipeline

Here is a miniature version of the idea. A registry maps pipe names to functions that take a value plus arguments, and applyPipes runs a chain left to right, like the template compiler does. The formatting uses the standard Intl objects, fixed to en-US and UTC so the output is the same everywhere.

TypeScript A tiny pipe registry and chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice the last line: using an unknown pipe name is an error. In real Angular that is a compile-time error in an AOT build, not a surprise at runtime.

Pure and impure pipes

Angular pipes come in two kinds, and the difference affects performance and correctness.

A pure pipe (the default) is re-run only when its inputs change by identity: a different primitive value, or a different object or array reference. If the inputs are the same, Angular reuses the previous result without calling transform. This makes pure pipes cheap: they can sit in a long list without being called on every change detection pass.

The catch is that mutating an array or object in place does not change its reference. A pure pipe that filters an array will not notice tasks.push(newTask). With signals, the idiomatic fix is to produce a new array on updates (tasks.update((list) => [...list, newTask])), which also keeps your state easier to reason about.

An impure pipe (pure: false) is re-run on every change detection cycle. It sees mutations, but it can be expensive. The built-in async pipe is impure for a good reason, since it must reflect a stream's latest value; json and keyvalue are also impure, so they notice objects that were mutated in place. Avoid writing impure pipes unless you have no alternative, and prefer a computed() signal that derives the value (see Signals: signal, computed and effect).

Writing a custom pipe

A pipe is a class decorated with @Pipe that implements PipeTransform. In modern Angular pipes are standalone by default:

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

@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 40, ellipsis = '...'): string {
    return value.length <= limit ? value : value.slice(0, limit).trimEnd() + ellipsis;
  }
}

Import it in the component that uses it, then:

HTML
<p>{{ article().summary | truncate: 60 }}</p>
<p>{{ article().summary | truncate: 60 : ' [more]' }}</p>

Guidelines: keep transform a pure function of its arguments with no hidden state, no HTTP calls and no side effects; give pipes a clear lowerCamelCase name; and remember that for a one-off calculation used in a single place, a computed() in the component is simpler than a pipe. Pipes pay off when the same display rule appears in many templates.

The second stand-in shows pure versus impure behavior. A small runner decides whether to call transform again on each "change detection cycle", exactly according to the rule above.

TypeScript Pure versus impure pipes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

In the pure case the push is invisible (cycle 3 shows stale data) and the pipe runs only twice. The impure pipe sees everything, but it ran on every one of the four cycles.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does {{ 0.256 | percent }} display with the default en-US locale?

    The percent pipe multiplies by 100 and rounds with its default digit settings (1.0-0), so 0.256 becomes 26%.
  2. 2. A pure pipe filters an array. You call list.push(item) on the same array. What happens?

    Pure pipes run only when an input changes by identity. Mutating in place keeps the same reference, so create a new array instead.
  3. 3. How should you write {{ flag ? a : b | uppercase }} if you want uppercase applied to the whole result?

    The pipe operator binds more loosely than most operators but tighter than the ternary, so without parentheses it would apply to b only. Parentheses make the intent explicit.
  4. 4. What must a custom pipe class implement and be decorated with?

    A pipe is a class with the @Pipe decorator (giving it a template name) and a transform method, described by the PipeTransform interface.

Summary

  • A pipe formats a value inside a template: {{ value | pipeName: arg1 : arg2 }}, and pipes chain left to right.
  • Common built-ins: date, currency, number, percent, json, slice, keyvalue, case pipes and async; import them from @angular/common.
  • Add parentheses around a ternary before piping its result.
  • Pure pipes (the default) re-run only when an input changes by identity, so update arrays and objects immutably; impure pipes run on every cycle and should be rare.
  • A custom pipe is a @Pipe class with a transform method; keep it a side-effect-free function.
  • The runnable examples are stand-ins; the Angular snippets are read-only.

Next: Inputs and Outputs