TExcelTAD
Home › Angular › Custom Pipes

Custom Pipes

The built-in pipes cover dates, numbers and text casing. For anything specific to your app — shortening long text, showing file sizes, turning a timestamp into "3 min ago" — write your own pipe. A pipe is a class with a transform method, marked with the @Pipe decorator.

Anatomy of a pipe

Generate one with ng generate pipe truncate:

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

@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
  transform(value: string, max = 20, suffix = '…'): string {
    return value.length > max ? value.slice(0, max).trimEnd() + suffix : value;
  }
}
Part Meaning
@Pipe({ name: 'truncate' }) The name used in templates: {{ text | truncate }}
PipeTransform Interface that requires a transform method
First parameter The value on the left of |
Further parameters The pipe arguments: {{ text | truncate: 10 : '...' }}

Because transform is an ordinary method, you can test the logic in plain TypeScript before wiring it into a template:

ts · try it yourself
class TruncatePipe {
  transform(value: string, max = 20, suffix = '…'): string {
    return value.length > max ? value.slice(0, max).trimEnd() + suffix : value;
  }
}

const pipe = new TruncatePipe();
console.log(pipe.transform('Short title'));
console.log(pipe.transform('Understanding change detection in depth'));
console.log(pipe.transform('Understanding change detection in depth', 10, '...'));
Short title
Understanding change…
Understand...

Using the pipe in a component

Add the pipe class to the component's imports, just like a built-in pipe:

angular · try it yourself
import { Component, Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
  transform(value: string, max = 20, suffix = '…'): string {
    return value.length > max ? value.slice(0, max).trimEnd() + suffix : value;
  }
}

@Component({
  selector: 'app-articles',
  imports: [TruncatePipe],
  template: `
    @for (a of articles; track a) {
      <p>📄 {{ a | truncate: 24 }}</p>
    }
  `,
})
export class Articles {
  articles = [
    'Signals in practice',
    'Migrating a large app to standalone components',
    'Writing fast tests with TestBed and harnesses',
  ];
}

A file-size pipe

Pipes are great for unit conversions. This one turns a number of bytes into a readable string:

ts · try it yourself
class FileSizePipe {
  private units = ['B', 'KB', 'MB', 'GB', 'TB'];

  transform(bytes: number, decimals = 1): string {
    if (bytes < 1024) return `${bytes} B`;
    let value = bytes;
    let unit = 0;
    while (value >= 1024 && unit < this.units.length - 1) {
      value /= 1024;
      unit++;
    }
    return `${value.toFixed(decimals)} ${this.units[unit]}`;
  }
}

const size = new FileSizePipe();
for (const n of [512, 2048, 1_572_864, 5_368_709_120]) {
  console.log(n, '->', size.transform(n));
}
console.log(size.transform(1_572_864, 2));
512 -> 512 B
2048 -> 2.0 KB
1572864 -> 1.5 MB
5368709120 -> 5.0 GB
1.50 MB

Pure and impure pipes

By default a pipe is pure: Angular calls transform again only when the input value or an argument changes by reference. That makes pipes very efficient, but it has a consequence — if you push into an array, a pure pipe on that array won't re-run, because the array reference is the same.

Pure (default) Impure (pure: false)
Runs when Input reference or arguments change On every change detection cycle
Cost Low Potentially high
Use for Formatting, calculations from inputs Rare cases that depend on mutable or external state

The caching behaviour of a pure pipe is like memoising on the last arguments:

ts · try it yourself
function memoizeLast<A extends unknown[], R>(fn: (...args: A) => R) {
  let lastArgs: A | undefined;
  let lastResult: R | undefined;
  let calls = 0;
  const wrapped = (...args: A): R => {
    const same = lastArgs !== undefined && args.length === lastArgs.length && args.every((a, i) => a === lastArgs![i]);
    if (!same) {
      calls++;
      lastArgs = args;
      lastResult = fn(...args);
    }
    return lastResult as R;
  };
  return { wrapped, calls: () => calls };
}

const total = memoizeLast((items: number[]) => items.reduce((s, n) => s + n, 0));
const cart = [10, 20, 30];

console.log(total.wrapped(cart));
console.log(total.wrapped(cart)); // same reference: cached
cart.push(40);
console.log(total.wrapped(cart)); // mutated, same reference: stale!
console.log(total.wrapped([...cart])); // new reference: recomputed
console.log('transform calls:', total.calls());
60
60
60
100
transform calls: 2

Tip: Instead of making a pipe impure, update arrays and objects immutably ([...list, item]). With signals you do that anyway.

Test yourself

Which method must a custom pipe implement?

  1. format()
  2. pipe()
  3. transform()
  4. ngOnPipe()

A pure pipe receives an array; you call push() on that array. What happens?

  1. The pipe re-runs immediately
  2. The pipe does not re-run because the array reference did not change
  3. Angular throws an error
  4. The array is copied automatically

In {{ title | truncate: 10 : '...' }}, what is the second parameter of transform?

  1. title
  2. 10
  3. '...'
  4. truncate