Pure Pipes & Template Variables: Fast, Decoupled Angular Templates
Pure Pipes & References: Keep template logic snappy and decoupled using pure pipes and template reference variables.
When building views in Angular, it is tempting to drop helper methods directly into your component class and call them straight from the template (e.g., \{\{ calculateTax(item.price) \}\}). While it looks harmless, it is one of the most common ways to degrade an Angular app's performance.
To keep templates fast and decoupled from boilerplate class methods, Angular gives you two primitives:
- Pure Pipes (@Pipe(\{ pure: true \})): Memoized transform functions that recalculate only when their arguments change identity (===), preventing wasted work during change detection.
- Template Reference Variables (#var): In-template pointers to DOM elements, child components, or directives that let elements communicate without routing trivial state through the component class.
## 1. The Performance Trap: Functions in Templates
Notice what happens when a plain component method is called inside template interpolation or property bindings:
```ts
// ANTI-PATTERN: Avoid this in production templates
@Component({
template: `
@for (user of users(); track user.id) {
([...]);
formatFullName(user: User): string {
// Runs on EVERY SINGLE change detection pass!
return `${user.firstName} ${user.lastName}`;
}
computeLoyaltyDiscount(points: number): number {
// Repeated math / array operations on every event...
return points * 1.25;
}
}
```
### Why does this hurt performance?
Angular has no way of knowing whether a plain class method will return a different value on any given tick. Whenever an event fires on the page—a mouse move, a keystroke, a timer, or an HTTP callback—Angular re-executes formatFullName() and computeLoyaltyDiscount() for every single item in the list.
If you have 50 items and click a button elsewhere on the screen, those functions run 50 times.
If a hover listener fires mouse events, they run hundreds of times per second.
## 2. Pure Pipes: Built-In Memoization
A pipe is an isolated transformation function. By default, every pipe created in Angular is pure (pure: true is the default setting of @Pipe).
### 2.1 How Pure Pipes Work
Angular evaluates a pure pipe only when its input arguments change by reference (===):
- **Primitives (string, number, boolean):** Re-runs only when the actual value changes.
- **Objects / Arrays:** Re-runs only when the object reference changes. Mutating an internal property (e.g., user.name = 'New') without altering the parent object reference will not trigger a recalculation.
```text
Change Detection Ticks
│
Has input argument changed (===)?
│
┌─────────┴─────────┐
▼ ▼
[YES] [NO]
│ │
Run transform() Return CACHED value
& cache result (Zero CPU cost)
```
### 2.2 Writing a Standalone Pure Pipe
```ts
// src/app/pipes/loyalty-discount.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'loyaltyDiscount',
standalone: true,
pure: true // Default setting: memoizes based on arguments
})
export class LoyaltyDiscountPipe implements PipeTransform {
transform(points: number, multiplier = 1.25): number {
// Runs strictly when `points` or `multiplier` changes
return Math.floor(points * multiplier);
}
}
```
### 2.3 Using It in a Component
```ts
// src/app/users/user-list.component.ts
import { Component, signal } from '@angular/core';
import { LoyaltyDiscountPipe } from '../pipes/loyalty-discount.pipe';
@Component({
selector: 'app-user-list',
standalone: true,
imports: [LoyaltyDiscountPipe],
template: `
@for (user of users(); track user.id) {
```
```ts
export class HeaderComponent {
onSearch(query: string): void {
console.log('Searching for:', query);
}
}
```
The component class remains clean—no throwaway searchTerm = '' properties required when you only care about the value at the moment the button is clicked.
### 3.2 Referencing a Child Component
Placed on a component tag, a template variable points directly to the component instance, exposing its public API:
```ts
// Child Component
@Component({
selector: 'app-video-player',
standalone: true,
template: ``
})
export class VideoPlayerComponent {
videoUrl = input.required();
play(): void { /* ... */ }
pause(): void { /* ... */ }
restart(): void { /* ... */ }
}
```
```html
```
You avoid needing @ViewChild(VideoPlayerComponent) or pass-through methods like onPlayClicked() \{ this.player.play(); \} in the parent class.
### 3.3 Referencing a Directive via exportAs
When an element has an attached directive, #var defaults to the DOM element. To reference the directive instead, assign the variable to the directive's exportAs name:
```ts
@Directive({
selector: '[appDropdown]',
standalone: true,
exportAs: 'dropdown' // Gives the directive a public template identifier
})
export class DropdownDirective {
isOpen = signal(false);
toggle(): void {
this.isOpen.update(v => !v);
}
close(): void {
this.isOpen.set(false);
}
}
```
```html
`
})
export class FileViewerComponent {
file = signal({ name: 'annual_report_2026.pdf', rawBytes: 15485760 });
copyToClipboard(text: string): void {
navigator.clipboard.writeText(text);
}
saveNewName(newName: string): void {
this.file.update(f => ({ ...f, name: newName.trim() }));
}
}
```
### Architectural Principles
- **Don't evaluate methods in interpolation:** Avoid \{\{ getDetails() \}\} inside loops or frequent bindings.
Reach for pure pipes for pure data transformations: Let Angular handle memoization automatically based on argument identity.
- **Keep classes focused on state and business logic:** Use #var to manage local element interactions, DOM method calls, and child component actions right in the template.
- **Bridge custom directives with exportAs:** Expose directive controllers directly to templates without writing intermediate event plumbing in the parent class.
{{ formatFullName(user) }}
Points: {{ computeLoyaltyDiscount(user.points) }}
}
`
})
export class UserListComponent {
users = signal
{{ user.firstName }} {{ user.lastName }}
Discount: {{ user.points | loyaltyDiscount:1.5 }}
}
`
})
export class UserListComponent {
users = signal([
{ id: 1, firstName: 'Aarav', lastName: 'Patel', points: 120 },
{ id: 2, firstName: 'Isha', lastName: 'Gupta', points: 340 }
]);
}
```
Now, clicking other buttons or triggering background events does not recalculate the discount. The cached result returns immediately.
### 2.4 Pure vs. Impure Pipes
| Trait | Pure Pipe (pure: true) | Impure Pipe (pure: false) |
| --- | --- | --- |
| Execution Trigger | Strictly when input arguments change identity (===) | On every single change detection tick |
| Performance | High (memoized results) | Low (identical to calling a function in the template) |
| Use Cases | Formatting strings, numbers, dates, currency, math | Observables (e.g., AsyncPipe), stateful streams |
| Default Setting | Yes | No (pure: false must be set explicitly) |
- **Rule of thumb:** Keep 99% of your pipes pure. If you need dynamic filtering over an array whose contents mutate without changing reference, prefer a computed() signal instead of an impure pipe.
## 3. Template Reference Variables (#var)
A template reference variable (declared with #name) creates an inline handle to an element, component, or directive directly in your template. This keeps DOM operations and component coordination out of the TypeScript class.
A template reference can target:
- A raw HTML DOM Element
- A Child Component instance
- A Directive instance (via exportAs)
### 3.1 Referencing a DOM Element
Access native DOM properties and methods without querying via document.querySelector or @ViewChild:
```html
@if (menuRef.isOpen()) {
}
```
## 4. Putting Both Together: An Inline File Card
Here is how pure pipes and template reference variables collaborate to build an interactive, decoupled file card:
### The Pipe
```ts
// src/app/pipes/file-size.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'fileSize',
standalone: true
})
export class FileSizePipe implements PipeTransform {
transform(bytes: number, precision = 2): string {
if (bytes === 0) return '0 Bytes';
const units = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const k = 1024;
const i = Math.floor(Math.log(bytes) / Math.log(k));
const val = parseFloat((bytes / Math.pow(k, i)).toFixed(precision));
return `${val} ${units[i]}`;
}
}
```
### The Component Template
```ts
// src/app/files/file-viewer.component.ts
import { Component, signal } from '@angular/core';
import { FileSizePipe } from '../pipes/file-size.pipe';
@Component({
selector: 'app-file-viewer',
standalone: true,
imports: [FileSizePipe],
template: `
