Contents
@defer: When Angular Finally Understood Lazy Loading—The Problem and Solution (Part 1)

@defer: When Angular Finally Understood Lazy Loading

“And in version 17, Angular said: Let there be @defer...” ✨

For years we suffered. Router-based loading worked, but everything had to go into routes. Dynamic imports worked, but needed 50 lines of boilerplate. NgComponentOutlet worked, but memory leaks lurked around every corner.

Then Angular 17 brought @defer blocks, and suddenly it made sense.


Prologue: lazy-loading horror stories

Every Angular developer has a traumatic experience. Here are mine:

typescript
// 2016: "Just lazy-load the route"
Developer: "I want to lazy-load this chart component"
Angular: "Daj ho do samostatnej route!"
Developer: "But it is on the same page..."
Angular: "NEW ROUTE!"
Developer: "..."

// 2019: "Use a dynamic import"
Developer: "OK, I will use a dynamic import..."
*writes 50 lines of boilerplate*
Developer: "This is tedious..."

// 2022: "Try NgComponentOutlet"
Developer: "I will try NgComponentOutlet"
*manages ViewContainerRef, ComponentFactory and manual cleanup*
Developer: "I only wanted to lazy-load a chart..."

// 2023: Angular 17 arrives
Developer: "@defer blocks?!"
*writes three lines*
Developer: "WHAT IS THIS MAGIC?!"

Chapter 1: The old ways (also known as pain)

Before the solution, let's see what we went through. Only then can we appreciate @defer.

Way #1: Router-based lazy loading

The only “official” way before Angular 17. It was an experience.

typescript
// app.routes.ts
const routes: Routes = [
  {
    path: 'dashboard',
    loadComponent: () =>
      import('./dashboard/dashboard.component')
        .then(m => m.DashboardComponent)
  },
  {
    path: 'heavy-chart',  // Wait... a separate route?
    loadComponent: () =>
      import('./charts/heavy-chart.component')
        .then(m => m.HeavyChartComponent)
  }
];

// dashboard.component.ts
@Component({
  template: `
    <h1>Dashboard</h1>

    <!-- Want to show the chart? Navigate to it! -->
    <a routerLink="/heavy-chart">Show chart</a>

    <!-- Or hack it with router-outlet? -->
    <router-outlet name="chart"></router-outlet>
  `
})

What was wrong:

❌ The chart needs its own route (why?!)
❌ Cannot conditionally show it on the same page
❌ The URL changes when the component loads
❌ Managing multiple outlets is a nightmare
❌ Over-engineering for simple lazy loading

The reality was worse:

typescript
// What we wanted:
"Show the chart when the user clicks a button"

// What we got:
routes: [
  { path: 'dashboard', component: Dashboard },
  { path: 'dashboard/chart', component: Chart },  // A separate route!
  { path: 'dashboard/stats', component: Stats },  // Another route!
  { path: 'dashboard/table', component: Table },  // Yet another!
]

// URL hell:
/dashboard
/dashboard/chart
/dashboard/stats
/dashboard/table

// Developer (in tears): "I only wanted conditional rendering..."

Way #2: Dynamic imports + ViewContainerRef

When the router was not enough, we reached for this—and regretted it.

typescript
@Component({
  template: `
    <button (click)="loadChart()">Load chart</button>
    <ng-container #chartContainer></ng-container>
  `
})
export class DashboardComponent implements OnDestroy {
  @ViewChild('chartContainer', { read: ViewContainerRef })
  container!: ViewContainerRef;

  private componentRef?: ComponentRef<any>;

  async loadChart() {
    // 1. Dynamic import
    const { HeavyChartComponent } = await import(
      './charts/heavy-chart.component'
    );

    // 2. Or use a newer approach
    this.componentRef = this.container.createComponent(
      HeavyChartComponent
    );

    // 3. Pass inputs manually
    this.componentRef.instance.data = this.chartData;

    // 4. Subscribe to outputs manually
    this.componentRef.instance.chartClick.subscribe(
      data => this.handleChartClick(data)
    );

    // 5. Run change detection
    this.componentRef.changeDetectorRef.detectChanges();
  }

  ngOnDestroy() {
    // 6. Manual cleanup (forget it = memory leak!)
    this.componentRef?.destroy();
  }
}

// Total: 40+ lines for simple lazy loading
// Pain level: HIGH 😤

Problems:

❌ Too much boilerplate
❌ Manual lifecycle management
❌ Easy to create memory leaks
❌ Passing inputs/outputs is painful
❌ Change detection issues
❌ Testing is a nightmare

Way #3: “I'll build my own framework”

The moment a developer lost hope and decided to solve it alone.

typescript
// lazy-load.service.ts (100+ riadkov)
@Injectable({ providedIn: 'root' })
export class LazyLoadService {
  private cache = new Map<string, Type<any>>();

  async loadComponent(path: string): Promise<Type<any>> {
    if (this.cache.has(path)) {
      return this.cache.get(path)!;
    }

    const module = await import(path);
    const component = Object.values(module)[0] as Type<any>;
    this.cache.set(path, component);
    return component;
  }

  // ... 80 more lines of utility methods
}

// Every developer reinvents the wheel
// Each implementation is slightly different
// Maintenance is painful

Typical progression:

Week 1: "I will build my own elegant lazy-load service!"
Week 2: "Hmm, this is getting complicated..."
Week 3: "Edge cases. Edge cases everywhere..."
Week 4: "Maybe Angular should support this natively?"
Week 5: *Angular 17 is released*
Week 6: "...well, damn." 🤦

Chapter 2: Revelation

Then Angular 17 and @defer blocks arrived. The world was never the same.

Basic syntax

This is what we always wanted:

typescript
@Component({
  template: `
    <h1>Dashboard</h1>

    <!-- Old way: 40+ lines of code -->
    <!-- New way: 3 lines -->

    @defer {
      <app-heavy-chart [data]="chartData" />
    }
  `
})

YES. THAT IS ALL. 🎉 No ViewContainerRef, dynamic imports or manual cleanup. Just @defer.

With a placeholder

typescript
@Component({
  template: `
    @defer {
      <app-heavy-chart [data]="chartData" />
    } @placeholder {
      <div class="skeleton">Loading chart...</div>
    }
  `
})

// What happens automatically:
// ✅ Lazy-loads the component
// ✅ Shows the placeholder
// ✅ Replaces it when loaded
// ✅ No manual cleanup
// ✅ No memory leaks

With loading state and error handling

typescript
@Component({
  template: `
    @defer {
      <app-heavy-chart [data]="chartData" />
    } @loading (minimum 500ms; after 100ms) {
      <app-spinner />
    } @error {
      <div class="error">
        Could not load chart
        <button (click)="retry()">Try again</button>
      </div>
    } @placeholder (minimum 500ms) {
      <div class="skeleton"></div>
    }
  `
})

// Professional loading experience in 15 lines!
// No manual state management!
// No RxJS subscriptions!

When I first saw it, I thought it had to be a trick. It could not be that simple. But it was.


Chapter 3: Seven magic triggers

This is where @defer shines: seven different triggers that can be combined.

Trigger 1: on idle (default)

typescript
// Loads when the browser is idle
@defer {
  <app-analytics-widget />
}

// Uses requestIdleCallback under the hood
// Perfect for non-critical content

Trigger 2: on viewport

An absolute game changer for infinite scroll.

typescript
@Component({
  template: `
    <div class="posts">
      @for (post of visiblePosts; track post.id) {
        <app-post-card [post]="post" />
      }
    </div>

    @defer (on viewport) {
      <app-more-posts />
    } @placeholder {
      <div class="load-more">Scrolluj pre viac...</div>
    }
  `
})

// Uses the IntersectionObserver API automatically
// No manual observer setup!

Remember 50+ line IntersectionObserver implementations? Now it is three lines.

Trigger 3: on interaction

typescript
@defer (on interaction) {
  <app-comments [postId]="postId" />
} @placeholder {
  <button>Load comments ({{ commentCount }})</button>
}

// Click the button → load the component
// Perfect for "show more" patterns!

Trigger 4: on hover

typescript
@defer (on hover) {
  <app-user-card [userId]="userId" />
} @placeholder {
  <div class="avatar">
    <img [src]="avatarUrl" />
  </div>
}

// Hover over avatar → load the full user card
// Perfect for tooltips!

Trigger 5: on timer

typescript
@defer (on timer(5s)) {
  <app-newsletter-popup />
}

// Loads after 5 seconds
// No setTimeout boilerplate!

Trigger 6: when condition

typescript
@defer (when isUserPremium()) {
  <app-premium-features />
} @placeholder {
  <div>Premium features (upgrade for access)</div>
}

// Reactive lazy loading!
// Funguje so signals!

Trigger 7: combine them

typescript
@defer (
  on interaction;      // ALEBO
  on viewport;         // ALEBO
  on timer(10s);       // ALEBO
  when userScrolled()  // ALEBO
) {
  <app-heavy-chart />
}

// Loads when ANY condition is true

Bonus: prefetching

typescript
@defer (
  on interaction;           // Render on click
  prefetch on hover         // Ale stiahni pri hover!
) {
  <app-expensive-component />
} @placeholder {
  <button>Show details</button>
}

// What happens:
// 1. User hovers over button → download chunk in background
// 2. User clicks → render IMMEDIATELY (already downloaded!)
// 3. User thinks you are a genius ⚡

In the next part: real comparisons, advanced patterns, pitfalls and a migration strategy.

All articles