Video lecture
Watch on YouTube(opens in a new tab)Sub topic 20
Lazy-Loading Template Sections with @defer
This chapter assumes you are comfortable with standalone components and the imports array, the built-in control flow blocks (@if, @for), template reference variables, and reading signals in templates. You should also know what a JavaScript bundle is and roughly how the Angular CLI builds one.
Why Defer Part of a Template
Each component listed in imports usually ends up in the same JavaScript chunk as the component that imports it. If a page has a heavy chart, a comments widget, or a map below the fold, the browser downloads and parses that code before the page can become interactive, even when the user never scrolls to it.
A @defer block wraps a section of a template. The Angular compiler moves the standalone components, directives, and pipes used only inside that block into a separate chunk. At runtime that chunk loads only when a trigger you choose fires. Until then, Angular renders nothing, or a placeholder you provide.
The Four Blocks
A deferrable view has one required block and three optional companions:
| Block | Purpose | Its dependencies are |
|---|---|---|
| `@defer` | The real content, loaded lazily | Deferred (separate chunk) |
| `@placeholder` | Shown before the trigger fires | Eager |
| `@loading` | Shown while the chunk downloads | Eager |
| `@error` | Shown if the chunk fails to load | Eager |
The companion blocks are bundled eagerly, so keep them light. Plain HTML is ideal.
A Worked Example
The article page below defers its comments section until the user scrolls to it. To reduce the wait, it starts fetching the code as soon as the browser is idle.
// comments.component.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-comments',
template: `
<h2>Comments</h2>
<ul>
@for (c of comments(); track c) {
<li>{{ c }}</li>
}
</ul>
`
})
export class CommentsComponent {
comments = signal(['Great article!', 'Thanks for writing this.']);
}// article.component.ts
import { Component } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-article',
imports: [CommentsComponent],
template: `
<article>
<h1>Understanding @defer</h1>
<p>Long article text...</p>
</article>
@defer (on viewport; prefetch on idle) {
<app-comments />
} @placeholder (minimum 500ms) {
<p>Comments appear when you scroll here.</p>
} @loading (after 100ms; minimum 1s) {
<p>Loading comments...</p>
} @error {
<p>Comments could not be loaded.</p>
}
`
})
export class ArticleComponent {}CommentsComponent is still listed in imports. The compiler sees that it is used only inside @defer and splits it out automatically. You do not write a dynamic import() yourself.
The timing parameters prevent flicker:
@placeholder (minimum 500ms)keeps the placeholder on screen for at least 500 ms after it first renders.@loading (after 100ms; minimum 1s)shows the loading block only if loading takes longer than 100 ms. Once it appears, it stays for at least 1 second. On a fast network the user goes straight from placeholder to content.
Triggers
Triggers decide when loading starts. If you specify none, the default is on idle.
| Trigger | Fires when |
|---|---|
| `on idle` | The browser is idle (`requestIdleCallback`) |
| `on viewport` | The placeholder (or a referenced element) enters the viewport |
| `on interaction` | The user clicks or presses a key on the element |
| `on hover` | The pointer enters the element, or it receives focus |
| `on immediate` | Right after the non-deferred content finishes rendering |
| `on timer(2s)` | After the given delay |
| `when expr` | A template expression becomes truthy |
Several triggers combine with OR semantics: @defer (on viewport; on timer(5s)) loads on whichever happens first. Prefetch triggers use the same vocabulary behind the prefetch keyword. They download the chunk without rendering it.
Targeting another element
viewport, interaction, and hover watch the placeholder by default. You can point them at any element in the same template with a template reference variable:
import { Component } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-lazy-comments',
imports: [CommentsComponent],
template: `
<button #showComments>Show comments</button>
@defer (on interaction(showComments); prefetch on hover(showComments)) {
<app-comments />
}
`
})
export class LazyCommentsComponent {}Hovering prefetches the chunk, so by the time the user clicks, the code is often already in the browser cache.
Conditional loading with when
import { Component, signal } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-admin-panel',
imports: [CommentsComponent],
template: `
<button (click)="isAdmin.set(true)">Log in as admin</button>
@defer (when isAdmin()) {
<app-comments />
} @placeholder {
<p>Admin tools are hidden.</p>
}
`
})
export class AdminPanelComponent {
isAdmin = signal(false);
}Gotchas and Failure Modes
Dependencies that silently stay eager
A dependency is deferred only if all of these are true:
- It is standalone. NgModule-based components cannot be deferred.
- It is not referenced anywhere else in the same file outside a
@deferblock. That includes eager parts of the template,viewChildqueries, or a type used in class code. Any such reference forces it into the main chunk.
Nothing warns you when this happens. Check the build output: ng build lists lazy chunks, and a missing chunk means the split did not occur.
Placeholder shape requirements
When on viewport, on interaction, or on hover has no explicit target, the placeholder must contain exactly one root element. Angular attaches its observer or listener to that element. A bare text node or two sibling elements causes an error.
Layout shift
If the placeholder is much shorter than the real content, the page jumps when the content arrives. Give the placeholder roughly the final size, for example with a fixed min-height.
Nested defer cascades
Nested @defer blocks with the same immediate trigger fire one after another, which causes a waterfall of network requests. Use different triggers for nested blocks, or flatten them.
Server-side rendering
During SSR and static prerendering, Angular renders the @placeholder (or nothing) and ignores triggers. Content that matters for SEO should therefore not live inside @defer. Angular 19 and later add incremental hydration. With provideClientHydration(withIncrementalHydration()), you can write hydrate on viewport so the server renders the full content and the client hydrates it lazily.
Testing
TestBed plays deferred blocks through by default. To control the states yourself, configure deferBlockBehavior: DeferBlockBehavior.Manual, get blocks with fixture.getDeferBlocks(), and call block.render(DeferBlockState.Complete) or DeferBlockState.Placeholder.
Deciding What to Defer
Good candidates are large, below-the-fold, or rarely used: charts, rich text editors, maps, dialogs opened by a button, and admin-only tools. Poor candidates are small components (the extra request costs more than it saves), content visible on first paint (you add latency to the most important pixels), and content needed for SEO without incremental hydration.
Exercise
A product page shows a ReviewsComponent inside @defer (on viewport) { <app-reviews /> } @placeholder { <span>Reviews</span> <span>below</span> }. The class also declares reviews = viewChild(ReviewsComponent);. Name the two problems with this setup and how to fix each.
Show answer
First, the placeholder has two root elements, so the implicit viewport trigger has no single element to observe and Angular throws an error. Wrap both spans in one element, such as a div, or target a separate element with on viewport(ref). Second, the viewChild(ReviewsComponent) query references the class outside the deferred block, so the compiler keeps ReviewsComponent in the eager bundle and no lazy chunk is produced. Remove the class-typed query, or query by a template reference name instead of by class, so the component is referenced only inside @defer.
Exercise
You want a heavy chart to start downloading two seconds after the page loads, but to render only when the user scrolls to it. Write the @defer opening line.
Show answer
@defer (on viewport; prefetch on timer(2s)) {. The prefetch trigger downloads the chunk after two seconds without rendering it, and the viewport trigger renders the chart when its placeholder becomes visible.