Sub topic 6
How triggers decide when loading starts
A @defer block does not load its content by itself. A trigger is the condition that starts the load. This chapter covers how triggers work in general: the syntax, the rules for combining them, what each kind watches, and what happens after one fires. The later chapters on specific triggers build on this model.
This chapter assumes you know these things:
- Standalone components and the
importsarray. - Angular template syntax, including
@ifand@for. - What a JavaScript bundle and a lazy-loaded chunk are.
What a trigger does
A deferred block moves through a fixed set of states. A trigger controls only one transition, from the initial state to the loading state. The block starts as a placeholder (or as nothing, if you wrote no @placeholder). When a trigger fires, Angular starts downloading the dependency chunk. It then renders the content, or the @error block if the download fails.
Two consequences follow from this model.
- A trigger starts a load. It does not decide how long the load takes, and it does not show or hide the content on its own.
- The transition happens once. After the block leaves the placeholder state, it does not return to it, whatever the trigger does afterwards.
Trigger syntax
Triggers go in parentheses after @defer. There are two families.
ontriggers react to something happening in the browser, such as idle time, scroll position or a click.whentakes a boolean expression and fires the first time it is true.
You can add a prefetch prefix to either family. A prefetch trigger downloads the chunk early but does not render anything. You can mix several triggers in one block by separating them with semicolons.
@defer (on viewport; on timer(10s); prefetch on idle) {
<app-reviews />
} @placeholder {
<p>Reviews will appear here.</p>
}This block has two main triggers and one prefetch trigger. The sections below explain how they combine.
The default trigger
If you write @defer with no parentheses, Angular uses on idle. The chunk loads once the browser reports that it has no urgent work, using requestIdleCallback where it is available. That is why the minimal example from the first chapter loads comments without any user action.
If you list any trigger of your own, the default no longer applies. @defer (on viewport) waits for the viewport and does not also load on idle.
Triggers combine with OR
When you list several main triggers, the first one to fire starts the load. Angular does not wait for all of them. This is useful for adding a fallback.
<button type="button" #showChart>Show chart</button>
@defer (on interaction(showChart); on timer(30s)) {
<app-chart />
} @placeholder {
<p>Press the button, or wait a moment.</p>
}The chart loads when the user clicks the button. If they do nothing, it loads after 30 seconds. After either one fires, the other has no effect.
Prefetch triggers combine in the same way, and they work separately from the main triggers. The prefetch list and the main list are independent, so a block can have one of each, or several of either.
The trigger catalog
| Trigger | Fires when | Needs an anchor element |
|---|---|---|
| `on idle` | The browser is idle | No |
| `on immediate` | Right away, without waiting for idle | No |
| `on timer(5s)` | The delay has elapsed | No |
| `on viewport` | The anchor enters the viewport | Yes |
| `on interaction` | The anchor is clicked or receives a keydown | Yes |
| `on hover` | The pointer enters, or the anchor receives focus | Yes |
| `when expr` | The expression is first truthy | No |
The first three need nothing from the template and rely only on time or the browser's scheduling. The other three watch an element. The following sections cover that anchor rule.
Time-based triggers
on immediate starts the load as soon as the template is rendered. It still splits the chunk off the main bundle, so the initial download is smaller. It does not wait for an idle moment, so use it when the content is needed almost at once but is not critical for the first paint.
on timer takes a duration in seconds or milliseconds, for example on timer(2s) or on timer(500ms). Treat the time as a delay from when the block is created, not as a precise schedule.
Anchors for viewport, interaction and hover
The three user-driven triggers watch an element, called the anchor. You can name the anchor in two ways.
- Pass a template reference variable, as in
on interaction(showChart). The element can be anywhere in the same template, including inside the@placeholder. - Pass nothing. The anchor is then the
@placeholdercontent.
The second form has a strict rule. The placeholder must exist and must have exactly one root element. With no placeholder, or with text and several sibling elements at the root, Angular cannot pick an element to watch, and compilation fails.
@defer (on viewport) {
<app-comments />
} @placeholder {
<div class="comments-placeholder">Comments</div>
}Here the div is the anchor. When it scrolls into view, Angular begins loading, and the placeholder is replaced by the real content after the load. The chapter on user triggers goes into viewport details.
A reference variable can name an element outside the defer block, which is the best choice when the thing the user touches is not the thing that is replaced. If the anchor is a button, the user can click it repeatedly, but only the first click matters.
The `when` trigger
when evaluates an expression during change detection. Because it is checked as part of normal rendering, it works with signals and component fields.
import { Component, signal } from '@angular/core';
import { PremiumPanelComponent } from './premium-panel.component';
@Component({
selector: 'app-account',
imports: [PremiumPanelComponent],
template: `
<button type="button" (click)="upgrade()">Upgrade</button>
@defer (when isPremium()) {
<app-premium-panel />
} @placeholder {
<p>Upgrade to see the premium panel.</p>
}
`,
})
export class AccountComponent {
protected readonly isPremium = signal(false);
protected upgrade(): void {
this.isPremium.set(true);
}
}The load starts when isPremium() first returns true. If the value goes back to false, the block does not go back to the placeholder. Use @if around the @defer when you need content that appears and disappears.
What happens after a trigger fires
After a main trigger fires, Angular does the following steps.
- It checks whether the chunk has already been fetched, for example by a prefetch trigger or another block using the same dependency.
- If it has not, it starts the download and shows the
@loadingblock when one exists, subject to itsafterandminimumtimings. - When the download succeeds, it renders the content. When it fails, it renders
@error.
The first step matters for prefetching. With prefetch on idle and a main trigger of on interaction, the chunk is usually already in the cache by the time the user clicks. The click then goes straight from placeholder to content, and the loading block never appears.
<button type="button" #showChart>Show chart</button>
@defer (on interaction(showChart); prefetch on idle) {
<app-chart />
} @placeholder {
<p>Press the button to see the chart.</p>
}A prefetch trigger can never render anything. If you write only prefetch on idle and no main trigger, the block uses the default on idle as its main trigger, so the block still renders.
Triggers and the server
During server-side rendering, the server cannot scroll, click or hover, and it does not wait for timers. Triggers do not fire there. The server renders the @placeholder content, and the browser starts the real trigger logic after the page loads. The SSR chapter covers this in detail. For now, remember that every deferred block needs a placeholder that makes sense as static HTML.
Common mistakes
- Using
on viewportwith no placeholder. The compiler reports an error because it has no anchor. Add a placeholder with a single root element, or pass a reference variable. - Referring to an element that is not in the template. A reference variable declared inside a different component's template, or inside an
@ifbranch you cannot see from the defer block, will not resolve. - Expecting
whento undo itself. The block stays rendered after the expression turns false. - Expecting AND logic.
@defer (on viewport; on timer(5s))loads at whichever comes first. To require two conditions, combine them in onewhenexpression, such aswhen ready() && visible(). - Adding
on immediateand expecting a smaller first paint. The bundle shrinks, but the content still arrives straight after rendering. It does not help the first paint much. - Writing a trigger on the template but also using the deferred component outside the block. If a deferred component is referenced anywhere else in the same file, the compiler keeps it in the main bundle, and the trigger only changes when the view appears.
Choosing a trigger
Match the trigger to what you know about the content.
- Content below the fold: use
on viewport, and considerprefetch on idle. - Content behind a button or a tab: use
on interactionwith a reference variable, plus a prefetch trigger. - Content a user probably wants when they approach it: use
on hover, which starts loading before the click. - Content that depends on application state: use
whenwith a signal. - Content that is simply not urgent: leave the default
on idle. - A guaranteed fallback: add
on timeras a second main trigger.
Exercise
A block is written as @defer (on viewport; on timer(5s); prefetch on hover(btn)). The user scrolls the block into view after 2 seconds and never touches btn. When does the load start, and what happens when the timer reaches 5 seconds?
Show answer
The load starts at the 2-second mark, when the viewport trigger fires first, because main triggers combine with OR and the first one wins. The prefetch trigger on btn never fired, so no early download happened. When the timer reaches 5 seconds it has no effect, because the block has already left the placeholder state and a block triggers only once.
Exercise
You write @defer (on interaction) { <app-chart /> } with no @placeholder block. Why does this fail, and give two ways to fix it.
Show answer
With no parameter, on interaction uses the placeholder's single root element as the anchor, and there is no placeholder, so the compiler has no element to watch. Fix 1: add a @placeholder with one root element, such as a button. Fix 2: pass a reference variable that points to an element in the template, for example on interaction(showChart).