Contents
@defer: When Angular Finally Understood Lazy Loading—Practice and Migration (Part 2)

Chapter 4: The Real Showdown

Let's compare old and new approaches in real scenarios.

Scenario: heavy chart component

Old way (80+ lines):

typescript
// You need routes, router outlet, navigation...
// Plus manual state management...
// Plus error handling...
// Total: 80+ lines and plenty of frustration

New way (10 lines):

typescript
@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:

typescript
@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

FeatureRouterDynamic import@defer
SetupRoutes config40+ lines3 lines
Loading statesManualManualBuilt in
Error handlingManualManualBuilt in
CleanupN/AManual (leak risk!)Automatic
TriggersNavigation onlyManual7+ types
PrefetchingManualManualBuilt 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

typescript
@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

typescript
@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 progressively

Network-aware loading

typescript
@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

typescript
// ❌ 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

typescript
// ❌ 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

typescript
// ❌ A ViewChild reference kills lazy loading
@ViewChild(ChartComponent) chart?: ChartComponent;

@defer {
  <app-chart />  // Loads immediately! ⚠️
}

Pitfall #4: Nested timers add up

typescript
@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

bash
ng generate @angular/core:standalone

Step 3: Replace gradually

typescript
// PRED
async loadChart() {
  const { ChartComponent } = await import('./chart');
  this.vcr.createComponent(ChartComponent);
}

// PO
@defer (on interaction) {
  <app-chart />
}

// 40 lines → 3 lines

Chapter 9: Real Results

Before @defer:

Bundle: 2.5 MB
First Contentful Paint: 3.2s
Lighthouse Score: 65

After @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

1

@defer

Use for component-level lazy loading.
2

router

Use the for page-level lazy loading.
3

Use both

for maximum performance.
4

Prefetch

for an immediate experience.
5

minimum times

Use to avoid flicker.
6

Monitor

bundle sizes.
typescript
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. 😅

All articles