Sub topic 3
Loading on a Condition with `when`
Assume you know standalone components, Angular template control flow, JavaScript bundles, and basic TestBed testing. This chapter focuses on conditional loading and the effects that follow.
Loading with `when`
The when trigger starts loading the first time its expression becomes true:
@defer (when user.isPremium) {
<app-premium-panel />
} @placeholder {
<p>Premium features are available to members.</p>
}Angular evaluates user.isPremium as the application runs. When it changes to true, Angular downloads the deferred chunk and renders the block. If it later changes to false, the block does not automatically disappear. Treat when as a one-way activation condition.
The components, directives, and pipes used only inside the block must be standalone and deferrable. Referencing the same dependency elsewhere can make it eager instead.
Prefetching Before Rendering
A prefetch trigger downloads the chunk without rendering it. Combine it with a separate rendering trigger:
<button type="button" #showChart>Show chart</button>
@defer (on interaction(showChart); prefetch when user.isPremium) {
<app-chart />
} @placeholder {
<p>Press the button to see the chart.</p>
}When the premium condition becomes true, Angular prefetches the code. The chart still renders only after the button interaction. Prefetching can reduce click latency, but it still uses bandwidth and cache space.
Avoiding Layout Shift
A layout shift occurs when content moves because a deferred view has a different size from its placeholder. Reserve a similar width and height in @placeholder. Defer expensive, below-the-fold, or interaction-driven features. Keep critical above-the-fold content eager when delaying it would make the page feel incomplete.
Testing Deferred Blocks
Manual defer behavior lets a test choose the block state directly:
import { TestBed, DeferBlockBehavior, DeferBlockState } from '@angular/core/testing';
import { PostComponent } from './post.component';
it('renders deferred content', async () => {
TestBed.configureTestingModule({
imports: [PostComponent],
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const fixture = TestBed.createComponent(PostComponent);
const blocks = await fixture.getDeferBlocks();
await blocks[0].render(DeferBlockState.Complete);
expect(fixture.nativeElement.querySelector('app-comments')).not.toBeNull();
});You can also render Placeholder, Loading, or Error to test each state.
Server-Side Rendering
During server-side rendering, Angular does not load the deferred chunk. The server renders the placeholder when one exists. After hydration, the browser evaluates the triggers and loads the block when appropriate. Provide useful placeholder content because it may be the first content sent to the user.
Exercise
What happens after a when condition becomes false following successful activation?
Show answer
The deferred block remains rendered. The condition activates the block once and does not undo that activation.