The Analogy: A Dry-Goods Finishing and Labeling Conveyor
Picture the last stretch of a dry-goods packing plant. A belt carries sacks of raw product past a row of fixed inline stations: one station stamps a grade onto the bag, the next prints a tidy weight label, another abbreviates the long product code into a short SKU. The sack that rolls off the end looks finished and shelf-ready, yet the bulk product inside the sack is exactly what went in - the stations only changed how it is presented, not the goods themselves. An Angular pipe is one of those stations: it takes an input value in a template expression, returns a transformed value for display, and never mutates the underlying data on your component.
Now watch how the plant decides when to re-run a station. A careful grader keeps the last crate's lot-code taped to its bench; when the next crate arrives bearing the same lot-code, the grader trusts its earlier reading and waves the crate through with the cached grade instead of weighing it again. This is a pure pipe: Angular re-invokes it only when the input reference (or a primitive value) actually changes, and otherwise reuses the last result. The memoization is what keeps a template with dozens of pipes cheap to re-render on every change-detection pass.
Down the line sits a different worker, an impure inspector who has been told the product can shift inside the sack at any moment, so they re-open and re-check every single sack on every single pass regardless of the lot-code. That is an impure pipe (pure: false): it runs on every change-detection cycle, which is occasionally necessary for live or internally-mutating data but is far more expensive, because change detection fires constantly.
The failure mode is a "pure" station that cheats. Suppose the grader is marked pure, but instead of only reading the crate it reaches in and rearranges the contents in place, leaving the lot-code untouched. Every downstream worker still sees the old lot-code, trusts its cache, and ships stale labels - the change is invisible because the memo key never moved. The Angular equivalent is a pure pipe that filters or sorts an array while callers mutate that same array in place: the array reference is unchanged, the pipe never re-runs, and the view silently drifts out of sync with the data.
Syntax or Core Structure
A pipe is applied inside a template expression with the pipe operator |: you write {{ value | pipeName }}, and arguments follow the pipe name after colons, as in {{ value | pipeName:arg1:arg2 }}. Pipes chain left to right, so {{ value | a | b }} feeds the output of a into b. Crucially the transformation is display-only - the component field keeps its original value, exactly as the labeling station leaves the bulk product untouched.
Angular ships several built-in pipes. uppercase and lowercase change case, slice returns a sub-range of a string or array, json dumps a value for debugging, and date / currency / number format according to a locale. The locale-aware formatters are convenient but their exact output depends on the active locale, so the deterministic examples below lean on uppercase and slice, whose results are fixed for a given input.
@Component({
selector: 'app-tag',
template: `
<p>{{ code | uppercase }}</p>
<p>{{ name | slice:0:3 | uppercase }}</p>
`
})
export class TagComponent {
code = 'ng-42';
name = 'angular';
}
The first line upper-cases ng-42. The second line first slices the first three characters of angular (giving ang), then pipes that into uppercase, showing how a chain reads left to right.
Output:
NG-42
ANG
Technical Depth: How Angular Decides to Re-Run a Pipe
Angular treats a pipe as a small memoized function bound to change detection. Whether it re-runs on a given cycle depends entirely on one flag: pure, which defaults to true.
Pure versus impure pipes
A pure pipe re-runs only when Angular detects a change to its input - a new reference for objects and arrays, or a new value for primitives. Because most values in a well-behaved app are replaced rather than mutated, this makes pipes almost free to leave in a template. An impure pipe (pure: false) runs on every change-detection pass, which can be many times per second; you opt into it only when the input mutates internally and you have no cheaper option.
| Aspect | Pure pipe | Impure pipe |
|---|---|---|
| Re-runs when | Input reference or primitive changes | Every change-detection pass |
| Default | Yes | No, set pure to false |
| Relative cost | Cheap, result memoized | Expensive, recomputed constantly |
| Best suited to | Immutable or replaced values | Live or internally-mutating data |
The single most important consequence: a pure pipe that receives an array or object will not notice in-place mutations to that array or object, because the reference it memoizes on never changes.
Writing a custom pure pipe
A custom pipe is a class marked with the @Pipe decorator and implementing PipeTransform, which requires a single transform method. The first argument is the input value; any further arguments are the colon-separated parameters from the template. Nothing about the class declares it "pure" - it is pure by default, and transform must stay a pure function of its arguments for that default to be safe.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
transform(value: string, limit: number): string {
return value.length > limit
? value.slice(0, limit) + '...'
: value;
}
}
Used in a template as {{ title | truncate:8 }}, it clips long strings and leaves short ones alone:
@Component({
selector: 'app-titles',
template: `
<p>{{ long | truncate:8 }}</p>
<p>{{ short | truncate:8 }}</p>
`
})
export class TitlesComponent {
long = 'Reactive Forms';
short = 'DI';
}
Reactive Forms is 14 characters, so it is cut to the first 8 (Reactive) with an ellipsis appended; DI is under the limit and passes through unchanged.
Output:
Reactive...
DI
Built-in pipes at a glance
Before writing a custom pipe, check whether Angular already ships one. The built-ins cover the most common transforms, and mixing them with your own in a chain is routine - {{ label | slice:0:3 | uppercase }} runs the built-in slice and then the built-in uppercase.
| Pipe | Purpose | Deterministic output |
|---|---|---|
| uppercase / lowercase | Change letter case | Yes for ASCII |
| slice | Sub-range of a string or array | Yes |
| json | Debug dump via JSON.stringify | Yes |
| date / currency / number | Locale-aware formatting | No, varies by locale |
| async | Unwrap an observable or promise | Depends on the source |
slice accepts start and end indices and works on arrays as well as strings, which makes it a quick way to window a list without adding a method to the component:
@Component({
selector: 'app-window',
template: `<p>{{ nums | slice:1:3 }}</p>`
})
export class WindowComponent {
nums = [10, 20, 30, 40];
}
The pipe returns the elements at indices 1 and 2, and Angular renders the resulting array as comma-joined text:
Output:
20,30
Real World Example: A Team Roster with a Filtering Pipe
A common temptation is to filter a list straight in the template with a custom pipe, keeping the component lean. Here a roster shows only active members by piping the array through an activeOnly pipe, and a button flips a member's status in place.
import { Pipe, PipeTransform, Component } from '@angular/core';
interface Member { name: string; active: boolean; }
@Pipe({ name: 'activeOnly' })
export class ActiveOnlyPipe implements PipeTransform {
transform(members: Member[]): Member[] {
return members.filter(m => m.active);
}
}
@Component({
selector: 'app-team',
template: `
<ul>
<li *ngFor="let m of members | activeOnly">{{ m.name }}</li>
</ul>
<button (click)="toggle('Lin')">Toggle Lin</button>
`
})
export class TeamComponent {
members: Member[] = [
{ name: 'Ada', active: true },
{ name: 'Lin', active: false },
{ name: 'Ravi', active: true }
];
toggle(name: string) {
const m = this.members.find(x => x.name === name);
if (m) m.active = !m.active;
}
}
On first render the pipe filters out the inactive Lin, leaving the two active members:
Output:
Ada
Ravi
Clicking "Toggle Lin" sets Lin.active = true, but it mutates an object inside the existing array without replacing the array itself. Because activeOnly is pure, Angular compares the array reference, finds it unchanged, and skips the pipe. The following plain-JavaScript model mimics that memoization to show what the user actually sees:
const members = [
{ name: 'Ada', active: true },
{ name: 'Lin', active: false },
{ name: 'Ravi', active: true }
];
let lastRef = null, cached = null;
function activeOnlyPure(arr) {
if (arr === lastRef) return cached; // pure: memoize on reference
lastRef = arr;
cached = arr.filter(m => m.active);
return cached;
}
console.log('first render: ' + activeOnlyPure(members).map(m => m.name).join(', '));
members[1].active = true; // mutate in place, same reference
console.log('after mutation: ' + activeOnlyPure(members).map(m => m.name).join(', '));
Output:
first render: Ada, Ravi
after mutation: Ada, Ravi
The roster renders correctly at first, and for a component whose list is only ever replaced wholesale - fetched fresh from a service, reassigned as a new array - this pipe behaves perfectly and stays cheap. The pure pipe is exactly the right tool when data arrives as new immutable references.
The trouble is that this particular component invites mutation: toggle reaches into the array and flips a boolean on an existing object, the packing-plant grader rearranging a crate's contents while leaving its lot-code untouched. Lin is now active in the data, yet the memoized pipe still returns the old two-name result, and the view quietly lies.
Developers usually discover this only when a checkbox or toggle mysteriously fails to update a filtered list, then "fix" it by marking the pipe pure: false. That works, but now the filter runs on every change-detection pass across the whole list, which is precisely the cost a pure pipe was meant to avoid.
The genuine design flaw is architectural: filtering and sorting do not belong in a pure pipe at all when the source data can mutate. The Angular team explicitly advises against filter and sort pipes for this reason. The robust fix is to compute the visible list in the component - recomputed in the toggle handler, or exposed as a getter over the current data - or to treat the array immutably and reassign a new reference on every change so a pure pipe re-runs by design. Hiding a filter behind a pure pipe couples correctness to an invisible reference-equality rule the rest of the code is free to violate.
Common Mistakes
- Filtering or sorting a list with a pure pipe. When the underlying array is mutated in place, the pipe's reference-based memo never invalidates, so the view drifts out of sync. Filter and sort in the component instead.
- Switching a pipe to impure just to force refreshes. It works, but the pipe now runs on every change-detection cycle, discarding the very memoization that made pipes cheap. Reach for it only as a last resort.
- Mutating the input value inside
transform. A pure pipe must be a pure function; mutating its argument corrupts the caller's data and defeats reference-equality checks elsewhere. - Doing expensive work inside an impure pipe. Sorting, HTTP-triggering, or deep-cloning in an impure pipe repeats on every cycle and will visibly stall the UI.
- Forgetting to register the pipe. A pipe must appear in an NgModule's
declarations(or a standalone component'simports), or the template throws a "no pipe found" error. - Assuming
dateandcurrencyoutput is stable. Their formatting depends on the active locale and timezone, so hard-coding expected strings makes tests brittle across environments. - Using a component method where a pipe belongs. A method call in the template such as
{{ format(x) }}re-runs on every change-detection pass with no memoization; an equivalent pure pipe runs only when its input changes. - Misjudging pipe precedence in an expression. The pipe operator binds loosely, so
{{ a ? b : c | uppercase }}pipes onlyc; wrap the whole expression or move the logic out of the template. - Reusing an
asyncpipe result across the template. Each| asynccreates its own subscription, so piping the same observable in several spots multiplies subscriptions; bind once and share via a template variable.
Best Practices
- Prefer pure pipes and keep every
transforma pure function of its arguments; this preserves memoization and makes the pipe trivially testable. - Do filtering and sorting in the component - a getter or a value recomputed when data changes - rather than hiding it in a pipe.
- Treat bound data as immutable: replace arrays and objects with new references on change so pure pipes re-run exactly when they should.
- Reserve impure pipes for genuinely live inputs and keep their work minimal, since the body executes on every change-detection cycle.
- Give each custom pipe one clear responsibility and a descriptive
name, the same discipline you would apply to a single-purpose function. - Lean on the built-in pipes (
date,currency,number,slice,json,async) before writing your own; they are optimized and well tested. - Let
AsyncPipemanage observable subscriptions in the template so subscribe and unsubscribe happen automatically with the view's lifecycle. - Unit-test custom pipes by instantiating the class and calling
transformdirectly with fixed inputs, which needs no template or component harness.
Practice Exercises
- Build a custom pure pipe. Write an
initialspipe that turns a full name such asAda LovelaceintoAL. ImplementPipeTransform, keeptransformpure, and test it by calling the method directly with two or three fixed names. - Replace a template method with a pipe. Take a component that formats a value through a method call in its template and reimplement that formatting as a pure pipe. Note how the pipe runs only when its input changes, while the method ran on every change-detection pass.
- Reproduce and fix the stale-filter bug. Create a list rendered through a pure filtering pipe, then mutate an item in place and confirm the view does not update. Fix it twice: once by moving the filter into a component getter, and once by reassigning a new array reference on change.
- Write a deterministic
fileSizepipe. Convert a byte count intoB,KB, orMBusing fixed thresholds of 1024, and verify the boundaries (for example 512, 20480, and 5242880) produce stable strings with no locale-dependent formatting.