Sub topic 2
Your first @defer block
This chapter builds the smallest useful @defer block and shows what the compiler does with it. It assumes you can write standalone components with an imports array, use @if and @for in templates, and run ng build and read its output. Triggers, sub-blocks, and testing each get their own chapter, so this one only introduces them.
The smallest block
A @defer block wraps part of a template. Angular does not create the wrapped content when the parent component first renders. It waits, downloads the code the content needs, and then renders it in place.
@defer {
<app-comments />
}This block has no trigger, no placeholder, and no parameters. Three things follow from that:
- Default trigger. With no trigger given, Angular uses
on idle. Loading starts once the browser reports it has nothing urgent to do. Angular schedules this withrequestIdleCallback. - Empty until loaded. Nothing is rendered in the block's position until the code arrives. The block takes no space, so content below it moves down when
<app-comments />appears. The chapter on layout shift covers this. - No unloading. Once the content is rendered, it stays. The block does not go back to its initial state.
What the compiler does
@defer is a compile-time feature, not a runtime wrapper. When the compiler sees a @defer block, it looks at the components, directives, and pipes used inside it. If a dependency is used only inside the block, the compiler removes it from the component's static imports and replaces it with a dynamic import(). The bundler then emits that code as its own chunk.
Here is a component that uses this:
import { Component } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-post',
imports: [CommentsComponent],
template: `
<article>...</article>
@defer (on viewport) {
<app-comments />
} @placeholder {
<div class="comments-placeholder"></div>
}
`,
})
export class PostComponent {}You write nothing special in TypeScript. CommentsComponent stays in the imports array and keeps its normal import statement. The compiler sees that <app-comments /> appears only inside the @defer block and rewrites the generated code so the file is loaded lazily.
This example uses on viewport instead of the default trigger, and it adds a @placeholder block. The placeholder is what the user sees before loading starts. Without it, the area would be empty. Both are covered in later chapters. Here, note only that the main block and its dependency handling work the same with any trigger.
The lifecycle of a block
A deferred block moves through states. The names below are the ones Angular uses, and they also appear in the testing API later in the tutorial.
| State | Meaning |
|---|---|
| Placeholder | The trigger has not fired yet. The `@placeholder` content shows, if you wrote one. |
| Loading | The trigger fired and the chunk is downloading. The `@loading` content shows, if you wrote one. |
| Complete | The chunk arrived and the main content is rendered. |
| Error | The chunk failed to load. The `@error` content shows, if you wrote one. |
A block starts in the placeholder state. With only a main block and no sub-blocks, the states before Complete are all empty.
The key point is that the main bundle runs and renders before the chunk is requested. The user can see and use the page during that time.
Confirming that it loads separately
Do not assume the split happened. Check it in two places.
First, run a production build:
ng buildThe build output lists the initial chunks (files loaded at startup) and the lazy chunks (files loaded later). Before you add @defer, the code for CommentsComponent is part of the initial output. After you add it, a new lazy chunk appears and the initial total gets smaller. The exact file names depend on your Angular version and bundler, so compare the totals before and after rather than looking for a specific name.
Second, open the browser's developer tools, go to the Network tab, and reload the page. You should see the main files load first. A separate JavaScript file loads afterward, when the trigger fires. If your dev server is on, throttle the network to make the gap easier to see.
A development build can look different from a production build, because development builds may not split chunks the same way. Treat ng build output as the reference.
Rules for what can be deferred
The compiler defers a dependency only when it is safe to do so. The rules:
- The dependency must be standalone. A component, directive, or pipe that belongs to an NgModule cannot be deferred on its own, because the module still has to load as a whole.
- It must appear only inside
@deferblocks. If the same component is used anywhere else in the same template outside a block, or referenced directly in the component class (for example, in aviewChildquery that names the class), the static import has to stay. Then the code lands in the main bundle, and the@deferblock still works but saves nothing. - It must be in the component's
importsarray. This is how the compiler knows which dependencies belong to the template.
Rule 2 is the most common reason a split silently fails. The code still runs, and no error appears. The build output is the only signal, since the lazy chunk is missing or smaller than expected.
import { Component, viewChild } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-post-eager',
imports: [CommentsComponent],
template: `
@defer {
<app-comments />
}
`,
})
export class PostEagerComponent {
// This reference to the class forces a static import,
// so CommentsComponent stays in the main bundle.
comments = viewChild(CommentsComponent);
}Here @defer is present, but viewChild(CommentsComponent) uses the class as a value in the TypeScript file. The compiler keeps the import. Remove that query, or query it differently, to get the split back.
Inputs, outputs and state
Content inside the block works like any other template content once it renders. You can bind inputs and listen to outputs:
@defer {
<app-comments [postId]="postId" (reply)="onReply($event)" />
}Bindings are evaluated when the block renders, not before. If postId changes while the chunk is still loading, the component is created with the latest value. Only the template content is deferred. The parent's fields, services, and signals exist from the start.
Dependency injection also works as usual. A deferred component can inject services that the parent provides. If a service is only ever used by deferred components and is provided with providedIn: 'root', it can be tree-shaken into the lazy chunk, because nothing in the main bundle references it.
Nesting and combining with control flow
You can put @defer inside @if or @for, and you can nest blocks:
@if (post.hasComments) {
@defer {
<app-comments [postId]="post.id" />
}
}Each block is independent, with its own trigger and state. Inside @for, every iteration gets its own deferred block instance, but all of them share the same chunk, which downloads only once. If you nest one @defer inside another, the inner block's trigger starts only after the outer block has rendered.
Edge cases to keep in mind
- Failed downloads. Without an
@errorblock, a failed chunk download shows nothing and logs an error to the console. Add an@errorblock for anything the user needs to see. - Repeat visits. The browser caches the chunk, so the second time a block loads the content appears faster. The block still goes through its states.
- Server-side rendering. On the server, deferred content is not rendered in the main block. The placeholder is rendered instead. This is covered in a later chapter.
- Small components. A very small component is rarely worth a separate request. The extra round trip can cost more than the bytes you save.
Summary of the mechanism
You wrap content in @defer { ... }. The compiler finds dependencies used only inside the block and turns their imports into dynamic imports. The bundler writes them into a lazy chunk. At runtime, the block starts empty, waits for its trigger (idle by default), downloads the chunk, and renders the content. Verify the result in the build output and in the Network tab.
Exercise
A component's template has @defer { <app-chart /> } and CommentsComponent-style import of ChartComponent in imports. After ng build, the initial bundle did not shrink and no new lazy chunk appeared. The class body contains chart = viewChild(ChartComponent);. Why did the split not happen, and what are two ways to fix it?
Show answer
The viewChild(ChartComponent) call uses the class as a value in TypeScript, so the compiler keeps a static import and the dependency stays in the main bundle. The block still works at runtime but saves nothing. Fix it by removing the query, or by moving it into a different place that does not name the class from the parent (for example, query the deferred component from inside a small wrapper component that is itself deferred). After the change, rebuild and confirm that a lazy chunk appears and the initial total drops.
Exercise
What does a @defer block with no trigger and no sub-blocks do from the moment the page loads, and what does the user see before the content appears?
Show answer
It uses the default on idle trigger, so Angular waits until the browser is idle and then downloads the chunk and renders the content in place. Before that, the user sees nothing in the block's position, because there is no @placeholder, and the content below the block shifts down when the deferred content appears.