Defer loading with the defer block in Angular
Lazy load a heavy Angular component with an at-defer block and a trigger such as viewport, with placeholder and loading states in the template.
Splitting a component into its own chunk used to need router changes or dynamic imports. The @defer block does it in the template.
import { Component } from '@angular/core';
import { ReviewsComponent } from './reviews.component';
@Component({
selector: 'app-product',
imports: [ReviewsComponent],
template: `
<h1>Product</h1>
@defer (on viewport) {
<app-reviews />
} @placeholder {
<p>Reviews appear as you scroll.</p>
} @loading (minimum 300ms) {
<p>Loading reviews…</p>
} @error {
<p>Reviews could not be loaded.</p>
}
`,
})
export class ProductComponent {}Reviews appear as you scroll. (placeholder, before it is visible)
Loading reviews… (while the chunk downloads)
(the reviews list) (once loaded)The compiler moves everything the block uses into a separate bundle, and only if the component is standalone and used nowhere else outside deferred blocks. The on viewport trigger loads it when the placeholder enters the viewport. Others include on idle, on interaction and on timer, and when takes a condition. See Deferred loading.
A @placeholder is needed for the viewport trigger, since it observes that element. Do not defer content visible on first paint, as it would delay the largest element.