Template Splitting in Modern Angular: Deferred Views (@defer)
Deferred Views (@defer): Lazy-load template chunks declaratively right when they enter the viewport, during user interaction, or when the browser sits idle.
For years, lazy loading in single-page applications stopped dead at the router boundary. If a route hosted a 200 KB charting engine, a syntax-highlighted markdown editor, or a third-party feedback feed tucked far below the fold, that JavaScript had to ship in the initial page bundle anyway.
Modern Angular fixes this with Deferred Views (@defer)—a declarative, compiler-level mechanism that brings true lazy loading directly to the template layer.
With @defer, Angular's build pipeline (driven by esbuild) automatically carves standalone components, directives, and pipes into isolated, asynchronous JavaScript chunks. These chunks download and mount on demand—triggered by scroll position, user interaction, idle threads, or reactive state—without writing a single dynamic import() statement.
## 1. Route-Level Lazy Loading vs. Template-Level @defer
| Feature | Route-Level Lazy Loading (loadComponent) | Template Deferred Views (@defer) |
| --- | --- | --- |
| Granularity | Entire page or screen boundaries | Individual components, widgets, or DOM sections |
| Trigger Mechanism | URL changes & router events | Viewport intersection, idle cycles, hover, clicks, signals |
| State Handling | Manual loading resolvers or full-page spinners | Declarative @placeholder, @loading, and @error blocks |
| Prerequisites | Standalone component tied to a route file | Standalone component, directive, or pipe in a template |
| Bundle Splitting | Explicitly defined in route configurations | Automated by the Angular compiler (esbuild) |
## 2. Anatomy of a Deferred Block
A deferred view orchestrates four distinct UI states:
```html
@defer (triggers) {
} @placeholder (minimum 500ms) {
} @error {
}
```
### How the Sub-Blocks Interact
@defer (Required): Marks the heavy UI boundary that must be excluded from the parent's primary bundle.
@placeholder (Optional): Renders before the trigger condition evaluates. The minimum 500ms parameter guards against layout thrashing (Cumulative Layout Shift) if the chunk loads instantaneously.
@loading (Optional): Renders while the browser retrieves the chunk.
after 100ms: Prevents a flicker of the spinner if the chunk is served from browser cache.
minimum 300ms: Ensures the spinner stays visible long enough to avoid an unsettling visual blip on fast networks.
@error (Optional): Displays an inline fallback if chunk resolution fails (e.g., offline user or dropped connection).
## 3. Loading Triggers: Declarative (on) vs. Imperative (when)
Loading behavior is governed either by browser-level events (on) or custom reactive conditions (when).
### Declarative Triggers (on <trigger>)
| Trigger | Browser Mechanism | Common Use Cases |
| --- | --- | --- |
| on viewport | IntersectionObserver on the placeholder | Below-the-fold content, heavy dashboards, comment feeds |
| on idle | requestIdleCallback when main thread is free | Non-urgent telemetry, feedback cards (Default fallback) |
| on interaction | Click, key focus, or tap events | Dialogs, slide-out panels, rich input fields |
| on hover | Cursor enters target element bounding box | Preview tooltips, context menus |
| on timer(ms) | Time-delayed execution | Guided tour tooltips, delayed promotional callouts |
### Viewport-Based Lazy Loading (Below-the-Fold Optimization)
The most direct win for Core Web Vitals (improving LCP and Total Blocking Time) is deferring components until the user reaches them:
```ts
import { Component } from '@angular/core';
import { HeavyAnalyticsChartComponent } from './heavy-analytics-chart.component';
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [HeavyAnalyticsChartComponent],
template: `
@defer (on viewport) {
} @placeholder {
} @placeholder {
}
`
})
export class AuditComponent {
shouldShowReview = signal(false);
}
```
### Combining Multiple Triggers
You can comma-separate triggers; the block downloads when any of the conditions evaluate to true:
```html
@defer (on viewport, timer(5000ms)) {
} @placeholder {
}
```
## 4. Background Prefetching: Decoupling Fetch from Render
Downloading code and rendering code don't have to happen at the exact same moment. With prefetch, you can download the chunk quietly in the background during idle moments, ensuring immediate rendering when the user actually interacts:
```html
@defer (on hover(previewBtn); prefetch on idle) {
} @placeholder {
Hover button for quick preview
}
```
```text
Page Load ──> Main Thread Idle ──> [Silent Background Prefetch]
│
User hovers button 2 mins later
│
[Instant Render from Cache]
```
## 5. Architectural Rules for @defer Chunk Isolation
To ensure the Angular compiler successfully splits your component into an independent file, verify these two rules:
- **Standalone Requirement:** Target components, directives, and pipes must be standalone: true. Components declared inside an NgModule cannot be split by @defer.
- **No Direct Class References:** If you reference the child component's token inside the parent component's .ts class (such as via viewChild(HeavyChartComponent)), the compiler must pull the class into the main bundle, completely breaking code splitting.
```ts
// ❌ WRONG: Pulls the heavy class straight into the main bundle
export class BrokenComponent {
chart = viewChild(HeavyChartComponent);
}
// ✅ RIGHT: Clean separation
export class CleanComponent {
// Let @defer manage component lifecycle exclusively inside the template
}
```
## 6. Production Implementation: Multi-Strategy Page Layout
A complete enterprise view combining viewport loading, idle prefetching, and interaction triggers:
```ts
// src/app/features/reports/financial-report.component.ts
import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';
import { RevenueHeatmapComponent } from './components/revenue-heatmap.component';
import { PdfExportDialogComponent } from './components/pdf-export-dialog.component';
import { CustomerFeedbackFeedComponent } from './components/customer-feedback-feed.component';
@Component({
selector: 'app-financial-report',
standalone: true,
imports: [
DatePipe,
RevenueHeatmapComponent,
PdfExportDialogComponent,
CustomerFeedbackFeedComponent
],
template: `
@defer (on interaction(exportBtn); prefetch on idle) {
}
} @placeholder {
`,
styles: [`
.heatmap-skeleton {
height: 400px;
background: #e5e7eb;
display: grid;
place-items: center;
}
`]
})
export class FinancialReportComponent {}
```
## 7. Verifying Chunk Splitting in Build Output
Running ng build confirms how the build pipeline splits your template dependencies:
```bash
$ ng build
```
### Initial Chunk Files | Names | Raw Size
chunk-MAIN.js | main | 120.45 kB
chunk-POLYFILLS.js | polyfills | 33.12 kB
### Lazy Chunk Files | Names | Raw Size
chunk-REVENUE_HEATMAP.js | revenue-chart | 89.32 kB <-- @defer (on viewport)
chunk-PDF_EXPORT.js | pdf-dialog | 145.10 kB <-- @defer (on interaction)
chunk-FEEDBACK_FEED.js | feedback-feed | 18.40 kB <-- @defer (on idle)
The initial bundle stays lightweight, deferring costly dependencies until the user or runtime explicitly asks for them.
Loading chart area...
} @loading (after 100ms; minimum 300ms) {
Executive Dashboard
Scroll down to inspect detailed metrics...
Chart area reserved...
}
`
})
export class DashboardComponent {}
```
- **Crucial Rule:** The @placeholder element must reserve dimensional height or width via CSS. A placeholder with 0px height sits at the top of the DOM on initial load, causing the IntersectionObserver to trigger immediately and defeating the optimization.
### Triggering on External DOM Elements
Use a template reference variable (#ref) to trigger loading from an outside button or element:
```html
@defer (on interaction(editBtn)) {
Editor is closed.
} ``` - **Imperative State:** when <condition> When loading depends on business logic, permissions, or reactive signals, use when: ```ts @Component({ template: ` @defer (when shouldShowReview()) {Q3 Financial Statements
ARR: $12.4M
Growth: +24%
Revenue Heatmap
@defer (on viewport; prefetch on idle) {Loading Visual Heatmap...
} @loading (after 150ms; minimum 250ms) {
Fetching visualization engine...
} @error {
Chart unavailable offline.
}
