Contents
Chapter 4: The Real Showdown
Let's compare old and new approaches in real scenarios.
Scenario: heavy chart component
Old way (80+ lines):
// You need routes, router outlet, navigation...
// Plus manual state management...
// Plus error handling...
// Total: 80+ lines and plenty of frustrationNew way (10 lines):
@Component({
template: `
<button (click)="showChart.set(true)">Show chart</button>
@defer (when showChart()) {
<app-heavy-chart [data]="chartData()" />
} @loading {
<app-spinner />
} @error {
<div>Could not load chart</div>
}
`
})
export class DashboardComponent {
showChart = signal(false);
chartData = signal([/* data */]);
}Seriously. That is all.
Scenario: infinite scroll
Old way: 120+ lines with a manual IntersectionObserver, cleanup and loading state.
New way:
@Component({
template: `
<div class="posts">
@for (post of posts(); track post.id) {
<app-post [post]="post" />
}
</div>
@defer (on viewport) {
<app-more-posts (loaded)="handleMorePosts($event)" />
} @loading {
<div class="loader">Loading...</div>
} @placeholder {
<div class="sentinel">Scrolluj pre viac</div>
}
`
})
export class PostsComponent {
posts = signal<Post[]>([]);
handleMorePosts(newPosts: Post[]) {
this.posts.update(posts => [...posts, ...newPosts]);
}
}
// 30 lines. 4× less code. Zero memory leaks.Chapter 5: Comparison Matrix
| Feature | Router | Dynamic import | @defer |
|---|---|---|---|
| Setup | Routes config | 40+ lines | 3 lines |
| Loading states | Manual | Manual | Built in |
| Error handling | Manual | Manual | Built in |
| Cleanup | N/A | Manual (leak risk!) | Automatic |
| Triggers | Navigation only | Manual | 7+ types |
| Prefetching | Manual | Manual | Built in |
Verdict: @defer wins every category except one: the router is still needed for page-level navigation. For component-level lazy loading, @defer is king.
Chapter 6: Advanced Patterns
Skeleton loading with timing control
@defer (on viewport; prefetch on idle) {
<app-user-profile [userId]="userId()" />
} @placeholder (minimum 500ms) {
<!-- Prevents flicker -->
<div class="skeleton">
<div class="skeleton-avatar"></div>
<div class="skeleton-name"></div>
</div>
} @loading (minimum 500ms; after 100ms) {
<!-- Shows only if it takes longer than 100ms -->
<div class="skeleton shimmer">...</div>
}
// Professional UX without flicker!Progressive enhancement
@Component({
template: `
<!-- Core content (always loaded) -->
<article class="post">
<h1>{{ post.title }}</h1>
<div class="content">{{ post.content }}</div>
</article>
<!-- Enhancements (lazy loaded) -->
@defer (on viewport) {
<app-comments [postId]="post.id" />
}
@defer (on interaction) {
<app-share-buttons [post]="post" />
}
@defer (on hover; prefetch on idle) {
<app-related-posts [postId]="post.id" />
}
`
})
// Core content works immediately
// Enhancements load progressivelyNetwork-aware loading
@Component({
template: `
@defer (when isFastConnection()) {
<app-high-quality-images />
}
@defer (when isSlowConnection(); on interaction) {
<app-low-quality-images />
} @placeholder {
<button>Load images</button>
}
`
})
// Fast network? Load immediately.
// Slow network? Wait for interaction.Chapter 7: Pitfalls
Every superpower has limits. Here is what to watch.
Pitfall #1: It must be standalone
// ❌ WILL NOT work
@Component({
standalone: false, // NgModule komponent
})
export class OldComponent {}
@defer {
<app-old-component /> // Loads IMMEDIATELY! ⚠️
}
// ✅ WILL work
@Component({
standalone: true,
})
export class NewComponent {}
@defer {
<app-new-component /> // Lazy-loads correctly ✅
}Pitfall #2: Use outside @defer
// ❌ Problem
@defer {
<app-chart />
}
<app-chart /> // This too! Everything now loads immediately! ⚠️
// ✅ Solution: Different components
@defer {
<app-chart-heavy />
}
<app-chart-light />Pitfall #3: ViewChild kills lazy loading
// ❌ A ViewChild reference kills lazy loading
@ViewChild(ChartComponent) chart?: ChartComponent;
@defer {
<app-chart /> // Loads immediately! ⚠️
}Pitfall #4: Nested timers add up
@defer (on timer(2s)) {
<app-outer /> <!-- 2s -->
@defer (on timer(2s)) {
<app-inner /> <!-- 4s celkovo! -->
}
}Chapter 8: Migration Strategy
Step 1: Identify candidates
Good candidates: Below-the-fold content, heavy charts/tables, modal dialogs, comments and analytics widgets.
Bad candidates: Above-the-fold content, navigation and critical user information.
Step 2: Convert to standalone
ng generate @angular/core:standaloneStep 3: Replace gradually
// PRED
async loadChart() {
const { ChartComponent } = await import('./chart');
this.vcr.createComponent(ChartComponent);
}
// PO
@defer (on interaction) {
<app-chart />
}
// 40 lines → 3 linesChapter 9: Real Results
Before @defer:
Bundle: 2.5 MB
First Contentful Paint: 3.2s
Lighthouse Score: 65After @defer:
Bundle: 800 KB (-68%)
First Contentful Paint: 1.1s (-66%)
Lighthouse Score: 95 (+30)These are not marketing numbers; they are real production results.
Epilogue: Peace at Last
Before Angular 17:
Developer: "I want to lazy-load a component"
Angular: "Here are four complicated ways; pick one"
Developer: *cries*After Angular 17:
Developer: "I want to lazy-load a component"
@defer {
<app-component />
}
Developer: "...is that all?"
Angular: "That is all."
Developer: "I love you."Conclusion: Golden Rules
@defer
router
Use both
Prefetch
minimum times
Monitor
if (you.buildAngularApps()) {
migrate.toStandalone();
embrace.defer();
make.usersHappy();
}Written by an Angular developer who survived ViewContainerRef hell and IntersectionObserver nightmares, and now lives peacefully with @defer blocks.
P.S. If you still use NgComponentOutlet for lazy loading, please stop. @defer is better in every way. Try it and see. 😅