Sub topic 9
Loading on a condition with when
This chapter covers the when trigger of @defer. It assumes you already know the basic @defer block, the @placeholder, @loading and @error sub-blocks, and Angular signals. It also assumes you have read the overview of how triggers start loading.
What the when trigger does
The on triggers react to the browser: idle time, an element entering the viewport, a click, a hover. The when trigger reacts to your application state. You give it a template expression, and the first time that expression is truthy, Angular starts loading the deferred chunk and renders the block.
@defer (when user.isPremium) {
<app-premium-panel />
} @placeholder {
<p>Upgrade to see the premium panel.</p>
}Use when when the decision to load depends on something the browser cannot tell you. Examples are a feature flag, a finished login, a completed HTTP request, or a step in a wizard.
The one-way rule
A when condition is a one-time trigger. After the expression becomes truthy once, loading starts and the block moves forward through its states. If the expression later becomes false, the block does not go back to the placeholder and the content is not removed.
The following component shows this. The button flips a signal on and off, but the panel stays on screen after the first flip.
import { Component, signal } from '@angular/core';
import { PremiumPanelComponent } from './premium-panel.component';
@Component({
selector: 'app-account',
imports: [PremiumPanelComponent],
template: `
<button type="button" (click)="isPremium.set(!isPremium())">
Premium: {{ isPremium() ? 'on' : 'off' }}
</button>
@defer (when isPremium()) {
<app-premium-panel />
} @placeholder {
<p>Upgrade to see the premium panel.</p>
}
`,
})
export class AccountComponent {
readonly isPremium = signal(false);
}The first click makes isPremium() true. Angular downloads the chunk for PremiumPanelComponent and replaces the placeholder with the panel. The second click sets the signal to false, but nothing changes in the DOM.
Comparison with @if
Because when does not toggle, it solves a different problem from @if. The table lists the differences.
| Aspect | `@if (cond)` | `@defer (when cond)` |
|---|---|---|
| Direction | Two-way: removes content when the condition turns false | One-way: never reverts after the first truthy value |
| Code loading | Dependencies are in the main bundle | Dependencies move to a lazy chunk |
| Before the condition | Renders the `@else` block, if any | Renders the `@placeholder`, if any |
| Loading states | None | `@loading` and `@error` |
If you need both lazy loading and toggling, nest them. The @if controls visibility, and the @defer inside it controls when the code is fetched.
@if (panelOpen()) {
@defer (when panelOpen()) {
<app-settings-panel />
}
}In this example the chunk is requested the first time panelOpen() is true. After the chunk has loaded, closing and reopening the panel creates the component from the already loaded code, so there is no second download.
What counts as a condition
The expression is a normal template expression, evaluated in the context of the component that owns the template. It can read signals, fields and computed values, call methods, and use operators.
@defer (when items().length > 0) {
<app-item-table [items]="items()" />
}
@defer (when auth.status() === 'signed-in' && flags.newDashboard()) {
<app-new-dashboard />
}The expression is checked during change detection, so follow these rules:
- Keep it cheap. A method call runs on every pass until the trigger fires.
- Keep it free of side effects. Do not increment counters or start requests inside it.
- Use signals where you can. A signal read makes the dependency obvious and keeps the check inexpensive.
- Do not reference template variables declared inside the deferred block. The condition runs outside the block, so it cannot see them.
The condition is truthy-based, not strictly boolean. A non-empty string, a non-zero number or an object counts as true. For readability, write an explicit comparison when the value is not already a boolean.
A condition that is already true
If the expression is truthy the first time the template is checked, loading starts at once, as it would with on immediate. The placeholder may never be visible, and the block may render only after the chunk arrives. If you want to wait for idle time or visibility instead, use on idle or on viewport rather than a condition that starts out true.
Combining when with other triggers
You can list several triggers in one @defer, separated by semicolons. They behave as a logical OR: the first one that fires starts loading.
@defer (on viewport; when forceLoad()) {
<app-report />
} @placeholder {
<div class="report-placeholder"></div>
}Here the report loads when its placeholder scrolls into view. It also loads as soon as forceLoad() is true, for example after the user presses "Print", which needs the report even if it is off-screen. Combining triggers this way gives you a natural scroll-based path plus an explicit override.
Prefetching with a condition
The prefetch when form downloads the chunk without rendering it. It is useful when you can predict that the main trigger will fire soon.
<input type="search" [value]="query()" (input)="query.set($any($event.target).value)" />
@defer (when results().length > 0; prefetch when query().length > 2) {
<app-results-grid [rows]="results()" />
} @placeholder {
<p>Type to search.</p>
}When the user has typed three characters, the chunk starts downloading. By the time results arrive and results().length > 0 becomes true, the code is usually cached and the grid renders without a loading state. The main trigger and the prefetch trigger are separate: prefetching never renders anything.
Putting it together: a login-gated dashboard
This example uses a service-style signal for the signed-in state and shows a loading and error state.
import { Component, computed, signal } from '@angular/core';
import { AdminToolsComponent } from './admin-tools.component';
@Component({
selector: 'app-home',
imports: [AdminToolsComponent],
template: `
<button type="button" (click)="signIn()">Sign in as admin</button>
@defer (when isAdmin()) {
<app-admin-tools />
} @placeholder (minimum 300ms) {
<p>Admin tools are available to administrators.</p>
} @loading (after 100ms; minimum 500ms) {
<p>Loading admin tools...</p>
} @error {
<p>Admin tools could not be loaded.</p>
}
`,
})
export class HomeComponent {
private readonly role = signal<'guest' | 'admin'>('guest');
readonly isAdmin = computed(() => this.role() === 'admin');
signIn(): void {
this.role.set('admin');
}
}Regular users never download the admin code. This is a performance optimization, not a security boundary. The chunk is a public static file, so a determined user can still request it. Enforce access on the server.
Common errors
- Expecting the block to disappear. Setting the condition back to false does not unload the content. Wrap the block in
@ifwhen you need removal. - Expecting a retry. If the chunk fails and the
@errorblock shows, flipping the condition false and then true does not restart the download. Because the trigger has already fired, plan recovery separately, for example with a "Reload page" action in the error block. - Calling an expensive method in the condition.
when computeScore() > 10runs on each check until it fires. Move the work into acomputedsignal. - Using a non-signal field that changes outside change detection. If a plain property changes inside a callback that Angular does not track, the template may not be re-checked. In applications that rely on signals or zone-based detection, update state through signals so the condition is re-evaluated.
- Starting with a true condition and expecting a placeholder. The load begins immediately, so the placeholder may flash or never appear. Choose a different trigger if you want a delay.
- Referencing a variable that lives inside the block. The condition cannot read anything declared in the deferred content.
Choosing between when and the on triggers
Use when when the signal to load comes from your data or logic. Use on viewport, on interaction or on hover when it comes from the user's behavior in the page. Use on idle or on timer when you want time-based loading regardless of state. When both apply, combine them with a semicolon and add a prefetch trigger for the one you can predict.
Exercise
A component has @defer (when showChart()) { <app-chart /> } @placeholder { <p>Hidden</p> }. The user clicks a button that sets showChart to true, then clicks again to set it to false. What does the user see after the second click, and why?
Show answer
The chart stays on screen. A when trigger is one-way: once the expression has been truthy, loading starts and the block does not revert to the placeholder if the expression becomes false later. To remove the chart, wrap the @defer in an @if (showChart()).
Exercise
Write a @defer block that loads <app-map /> when the signal locationGranted() is true, and prefetches the chunk as soon as mapTabVisible() is true. Which of the two triggers renders the component?
Show answer
@defer (when locationGranted(); prefetch when mapTabVisible()) { <app-map /> }. Only the main trigger, when locationGranted(), renders the component. The prefetch when trigger only downloads the chunk ahead of time.