Blog

Part 27 · @defer and Performance in Angular: Lazy Loading and Smaller Bundles

The @defer block loads part of a page only when it’s needed. This part covers placeholders, loading and error blocks, triggers, prefetch, bundle budgets, NgOptimizedImage and how to read the build’s sizes.

The less code a browser has to download before it can show a page, the sooner the page appears. Most pages have parts nobody needs at first: a chart behind a button, reviews at the bottom, a help panel. Angular’s @defer block keeps the code for those parts out of the first download and fetches it when it’s needed.

This part covers @defer with its @placeholder, @loading and @error blocks, the triggers that decide when the code loads, prefetch, what has to be true for the code to really be split out, bundle budgets, and NgOptimizedImage for images. In Part 16 we loaded whole pages lazily with loadComponent. Here we do the same for a piece of a page. @defer is a block like @if from Part 4. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

Make two files. chart.ts stands in for a big component, like a chart library. It has a console.log at the top, outside the class. As in Part 16, code there runs once, when the browser loads the file.

// src/app/chart.ts
import { Component } from '@angular/core';

console.log('chart.ts loaded');

@Component({
  selector: 'app-chart',
  template: `<p>Sales: ▇▇▇▅▂</p>`,
})
export class Chart {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Chart } from './chart';

@Component({
  selector: 'app-root',
  imports: [Chart],
  template: `
    <h1>Report</h1>
    @defer (on interaction) {
      <app-chart />
    } @placeholder {
      <button>Show chart</button>
    }
  `,
})
export class App {}

App imports Chart the normal way, at the top of the file and in imports. Before you read on, guess. When the page opens, is chart.ts loaded in the console?

One thing first. A new project’s ng serve uses hot module replacement (HMR), which swaps changed code into the open page when you save. With HMR on, Angular loads every deferred file straight away, and the console says so:

NG0751: Angular has detected that this application contains `@defer` blocks and the hot module replacement (HMR) mode is enabled. All `@defer` block dependencies will be loaded eagerly. Find more at https://v22.angular.dev/errors/NG0751

The page still shows the placeholder, and the chart still waits for the click. Only the download has moved to page load, so chart.ts loaded appears at once.

To see when the code downloads, stop ng serve and start it with ng serve --no-hmr. Now the page shows:

Report
Show chart

and the console is empty:

Click Show chart. The page shows:

Report
Sales: ▇▇▇▅▂

and only now does the console show:

chart.ts loaded

App imports Chart, but the browser didn’t load chart.ts until the click. The @defer block changed what the import does.

What @defer does

When the compiler sees a component, directive or pipe used only inside a @defer block, it drops the normal import from the compiled code. In its place it writes a dynamic import, the import('./chart') from Part 16, that runs when the block needs the code. The build then puts chart.ts in a file of its own, a lazy chunk. You can see it in the build output. Here’s what ng build printed for these two files (your file names and sizes will differ):

Initial chunk files | Names         |  Raw size | Estimated transfer size
chunk-6WCZKQMY.js   | -             | 114.79 kB |                34.47 kB
main-57MJUIFE.js    | main          |  90.03 kB |                22.85 kB
styles-5INURTSO.css | styles        |   0 bytes |                 0 bytes

                    | Initial total | 204.82 kB |                57.32 kB

Lazy chunk files    | Names         |  Raw size | Estimated transfer size
chunk-QQKVZOYM.js   | chart         | 353 bytes |               353 bytes

ng serve --no-hmr lists the chunk too, under the same heading. Initial chunk files are what the browser downloads before it can show anything. Lazy chunk files wait until something asks for them. Our chart is tiny, so it saves almost nothing here. A real chart library can be most of a page’s code.

The block has up to four parts:

  • @defer { ... } is the content you want later.
  • @placeholder { ... } shows until the block’s trigger fires. A trigger is the event that starts loading, here on interaction: a click or a key press on the placeholder.
  • @loading { ... } shows while the chunk downloads.
  • @error { ... } shows if the chunk can’t be loaded.

Only the @defer part is deferred. Components used in the other three blocks are in the first download, because they have to be ready to show at once.

Here’s the click step by step, for a block that also has a @loading block (we add one in the next section):

App component Report Show chart @placeholder Loading chart… @loading Sales: ▇▇▇▅▂ @defer content: Chart click server chart chunk not loaded chart chunk loaded download placeholder on screen, chart chunk not downloaded trigger fired: Angular calls import() for the chunk @loading on screen while the chunk downloads chunk loaded, Chart created, the block shows its content The page renders. The @defer block shows its @placeholder You click the placeholder, and the interaction trigger fires @loading replaces the placeholder; the browser fetches the chunk The chunk arrives, and Chart replaces @loading

The placeholder holds the space. The trigger starts the download, and the content replaces whatever is showing.

Here are those steps in words, in case the animation doesn’t play for you:

  1. The page renders. Chart isn’t loaded, so the @defer block shows its @placeholder: the Show chart button.
  2. You click the button. That’s the interaction trigger, so Angular calls the dynamic import for the chart chunk.
  3. The @loading block replaces the placeholder while the browser downloads the chunk. Without one, the placeholder stays on screen until the chunk arrives.
  4. The chunk arrives. Angular creates Chart, and the block’s content replaces the loading text. The block stays that way: it never goes back to the placeholder.

@loading and @error

Our chunk loads too fast to see a loading message. @loading takes two optional settings that help with that, separated by a ;:

  • after 100ms: don’t show the loading block at all unless loading takes longer than 100 milliseconds. A fast load then goes straight from placeholder to content, with no flash of “Loading…”.
  • minimum 1s: once the loading block shows, keep it for at least 1 second, so it doesn’t flicker on and off.

@placeholder takes minimum too. Times are in ms or s. Here’s the same page with a @loading (minimum 1s) block and an @error block. chart.ts stays as it was.

// src/app/app.ts
import { Component } from '@angular/core';
import { Chart } from './chart';

@Component({
  selector: 'app-root',
  imports: [Chart],
  template: `
    <h1>Report</h1>
    @defer (on interaction) {
      <app-chart />
    } @placeholder {
      <button>Show chart</button>
    } @loading (minimum 1s) {
      <p>Loading chart...</p>
    } @error {
      <p>The chart couldn't load.</p>
    }
  `,
})
export class App {}

Click Show chart. Straight away the page shows:

Report
Loading chart...

A second later it shows:

Report
Sales: ▇▇▇▅▂

To see @error, the chunk has to fail. In real life that happens when the network drops, or when a new version of the site has replaced the old chunk files. To try it at home, make the file throw an error while it loads. The throw at the end runs when the browser loads the file:

// src/app/chart.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-chart',
  template: `<p>Sales: ▇▇▇▅▂</p>`,
})
export class Chart {}

throw new Error('chart.ts failed');

Click Show chart and wait. The page shows:

Report
The chart couldn't load.

Put chart.ts back the way it was before you go on. We’ll see what happens without an @error block in a worked example below.

Triggers: when the code loads

on interaction is one trigger. Here are all of them:

Trigger The block loads
on idle when the browser has nothing else to do. This is the default: @defer { ... } with no trigger means on idle.
on viewport when the placeholder scrolls into view.
on interaction when the user clicks the placeholder, or presses a key while it has focus.
on hover when the mouse moves over the placeholder, or it gets focus.
on immediate as soon as the rest of the page has rendered.
on timer(2s) after the given time.
when ready() when the expression becomes true.

You can list several, separated by ;. The block loads on whichever fires first: @defer (on viewport; on timer(5s)).

on viewport, on interaction and on hover watch the placeholder by default. You can point them at another element in the same template instead, with a template reference variable from Part 2: @defer (on hover(helpButton)) watches the element marked #helpButton. We’ll need that in a worked example.

Here’s on hover and on timer on one page, using the same chart.ts:

// src/app/chart.ts
import { Component } from '@angular/core';

console.log('chart.ts loaded');

@Component({
  selector: 'app-chart',
  template: `<p>Sales: ▇▇▇▅▂</p>`,
})
export class Chart {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Chart } from './chart';

@Component({
  selector: 'app-root',
  imports: [Chart],
  template: `
    <h1>Report</h1>
    @defer (on hover) {
      <app-chart />
    } @placeholder {
      <p>Point here to see the chart</p>
    }
    @defer (on timer(2s)) {
      <p>Tip: the chart covers the last five months.</p>
    } @placeholder {
      <p>...</p>
    }
  `,
})
export class App {}

When the page opens, it shows:

Report
Point here to see the chart
...

Move the mouse over Point here to see the chart, and wait two seconds. The page shows:

Report
Sales: ▇▇▇▅▂
Tip: the chart covers the last five months.

The second block holds plain HTML and no component. That’s allowed. There’s nothing to download, so it only delays when the content appears.

Angular checks a when expression each time it updates the template, so a signal works well there. It works one way only: once the block has loaded, it stays, even if the expression goes back to false. Exercise 3 tries that. Part 29 adds hydrate triggers, which are about pages rendered on the server.

prefetch: download early, show later

on interaction has a cost. The download starts at the click, so the user waits for it. prefetch splits the two jobs: one trigger downloads the code, the other shows the content. Change the block in the “Try this first” app.ts to this:

// src/app/app.ts
import { Component } from '@angular/core';
import { Chart } from './chart';

@Component({
  selector: 'app-root',
  imports: [Chart],
  template: `
    <h1>Report</h1>
    @defer (on interaction; prefetch on idle) {
      <app-chart />
    } @placeholder {
      <button>Show chart</button>
    }
  `,
})
export class App {}

The page still shows only the button:

Report
Show chart

But a moment after the page opens, the console shows:

chart.ts loaded

The browser fetched the chunk as soon as it was idle. Click Show chart, and the chart appears with no download to wait for:

Report
Sales: ▇▇▇▅▂

The prefetch trigger can be any of the triggers above: prefetch on hover, prefetch on viewport, prefetch when ....

When the code really goes into its own chunk

A component is deferred only if both of these are true:

  1. It’s standalone. Every component made the modern way is. A component declared in an NgModule is loaded eagerly even inside @defer.
  2. The file never uses it outside a @defer block. Not elsewhere in the template, not in a viewChild() query, not anywhere in the class.

The second rule is easy to break without noticing, and nothing warns you. Here’s App with a viewChild() query for the chart, from Part 10:

// src/app/app.ts
import { Component, viewChild } from '@angular/core';
import { Chart } from './chart';

@Component({
  selector: 'app-root',
  imports: [Chart],
  template: `
    <h1>Report</h1>
    @defer (on interaction) {
      <app-chart />
    } @placeholder {
      <button>Show chart</button>
    }
  `,
})
export class App {
  protected readonly chart = viewChild(Chart);
}

It builds, and the page still shows the button:

Report
Show chart

But the console shows this as soon as the page opens:

chart.ts loaded

viewChild(Chart) uses the Chart class in ordinary code, so the compiler has to keep the normal import, and chart.ts joins the first download. ng build has no lazy chunk to list any more:

Initial chunk files | Names         |  Raw size | Estimated transfer size
main-PKF45FCG.js    | main          | 211.94 kB |                57.88 kB
styles-5INURTSO.css | styles        |   0 bytes |                 0 bytes

                    | Initial total | 211.94 kB |                57.88 kB

The block still waits for the click to show the chart. It just has nothing left to download. Click Show chart, and the page shows:

Report
Sales: ▇▇▇▅▂

Check the build output for a lazy chunk with your component’s name whenever you add a @defer.

Two more ways to lose the chunk, from angular.dev: importing the component through an index.ts file that re-exports many things (a “barrel” file), and importing anything else from the component’s file into an eager file. Exercise 1 shows the second.

@defer and lazy routes

Part 16 did the same thing for whole pages:

{ path: 'about', loadComponent: () => import('./about').then((m) => m.About) },

Both end up as lazy chunks in the build output. Use loadComponent for a page that has its own URL. Use @defer for a part of a page: the page arrives quickly, and the heavy part follows.

Bundle budgets: a limit on the first download

It’s easy to add a library and not notice that the first download doubled. A budget is a size limit in angular.json that ng build checks every time. A new project has this, under "production":

"budgets": [
  {
    "type": "initial",
    "maximumWarning": "500kB",
    "maximumError": "1MB"
  },
  {
    "type": "anyComponentStyle",
    "maximumWarning": "4kB",
    "maximumError": "8kB"
  }
],

initial is the Initial total from the build output: everything before the page can show. anyComponentStyle limits each component’s own CSS. To see a budget fail, we set the initial limits to 150kB and 1MB and ran ng build on the “Try this first” app. The build still worked, with a warning:

▲ [WARNING] bundle initial exceeded maximum budget. Budget 150.00 kB was not met by 54.82 kB with a total of 204.82 kB.

With maximumError at 200kB, the build failed:

Application bundle generation failed. [4.677 seconds] - 2026-12-04T11:56:06.835Z

▲ [WARNING] bundle initial exceeded maximum budget. Budget 150.00 kB was not met by 54.82 kB with a total of 204.82 kB.


✘ [ERROR] bundle initial exceeded maximum budget. Budget 200.00 kB was not met by 4.82 kB with a total of 204.82 kB.

Three things to read in it:

  • The budget checks the raw size (204.82 kB here), not the smaller “estimated transfer size”.
  • “Was not met by 4.82 kB” is how far over you are.
  • A failed build stops a deploy that runs ng build. That’s the point: someone has to decide whether the new size is fine, then raise the budget on purpose.

A new project sets budgets only for the production configuration. ng serve uses the development configuration, which has none. Other types exist too, such as anyScript for every script file, lazy chunks included.

NgOptimizedImage: images that don’t slow the page

Images are often the biggest files on a page. NgOptimizedImage is a directive from @angular/common that sets the right loading attributes on an <img> for you, and checks your usage while you develop. You use it by writing ngSrc instead of src.

The image file goes in public/, which the app serves at /. Save this as public/cover.svg:

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="200" viewBox="0 0 300 200">
  <rect width="300" height="200" fill="#2f6f4f" />
  <rect x="20" y="20" width="260" height="160" fill="none" stroke="#f4e9c8" stroke-width="4" />
  <circle cx="150" cy="80" r="30" fill="#f4e9c8" />
  <text x="150" y="150" font-family="serif" font-size="28" text-anchor="middle" fill="#f4e9c8">
    The Garden
  </text>
</svg>
// src/app/app.ts
import { NgOptimizedImage } from '@angular/common';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  imports: [NgOptimizedImage],
  template: `
    <h1>The Garden</h1>
    <img ngSrc="/cover.svg" width="300" height="200" alt="Cover of The Garden" />
  `,
})
export class App {}

width and height are required, unless you use fill, which makes the image fill its parent element. Then you leave both out. They’re the image’s size in pixels, so the browser can keep the right space for it before it arrives. Without them the text below would jump down when the image loads.

This works, but once the image has loaded, Chrome logs an error in the console:

NG02955: The NgOptimizedImage directive (activated on an <img> element with the `ngSrc="http://localhost:4200/cover.svg"`) has detected that this image is the Largest Contentful Paint (LCP) element but was not marked "priority". This image should be marked "priority" in order to prioritize its loading. To fix this, add the "priority" attribute.

The Largest Contentful Paint (LCP) is the biggest thing the browser draws when a page first opens. How soon it appears is one of the main ways browsers and search engines measure a page’s speed. NgOptimizedImage gives every image loading="lazy" by default, which tells the browser it can wait. That’s right for images further down the page and wrong for the main one. priority fixes it:

// src/app/app.ts
import { NgOptimizedImage } from '@angular/common';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  imports: [NgOptimizedImage],
  template: `
    <h1>The Garden</h1>
    <img ngSrc="/cover.svg" width="300" height="200" priority alt="Cover of The Garden" />
  `,
})
export class App {}

The console is clean now. In the Elements tab you’ll see the attributes the directive added:

<img ngsrc="/cover.svg" width="300" height="200" priority="" alt="Cover of The Garden" loading="eager" fetchpriority="high" decoding="sync" ng-img="true" src="/cover.svg">

fetchpriority="high" asks the browser to fetch this image before others. Use priority on one image per page, the main one near the top. Angular warns (NG02966) if more than 10 images have it.

These checks run only in development builds. A production build skips them, so fix what they report while you work.

Measuring, honestly

@defer, lazy routes and budgets all aim at one number: the Initial total in the ng build output. Some ways to keep track of it:

  • Read the build output after every change that adds a library or a @defer. Look for your component’s name under “Lazy chunk files”. If it isn’t there, the code wasn’t split.
  • Measure production builds only. The same “Try this first” app came to 1.37 MB with ng build --configuration development, which skips minifying (shrinking) and removing unused code, and 204.82 kB with ng build. ng serve prints much smaller numbers because it serves Angular’s own code separately, so don’t read sizes from it. Your numbers will differ; compare builds of your own app, before and after.
  • Watch the Network tab in the browser’s developer tools while you click and scroll. Each lazy chunk shows up as a chunk-....js request at the moment it loads.
  • Use Lighthouse, in Chrome’s developer tools, for page-load measures like LCP. Run it on a production build, several times, and compare runs rather than trusting one.

We haven’t put any timings in this post, because they depend on your machine, your network and your app.

Worked example: a book page with reviews

Here’s a realistic page: a book’s cover and blurb at the top, and reviews further down that most visitors never scroll to. The reviews load when their placeholder scrolls into view. The tall .story box stands in for a long description.

// src/app/reviews.ts
import { Component } from '@angular/core';

console.log('reviews.ts loaded');

@Component({
  selector: 'app-reviews',
  template: `
    <h2>Reviews</h2>
    <p>Ana: A calm, lovely read.</p>
    <p>Ben: Slow start, great ending.</p>
  `,
})
export class Reviews {}
// src/app/app.ts
import { NgOptimizedImage } from '@angular/common';
import { Component } from '@angular/core';
import { Reviews } from './reviews';

@Component({
  selector: 'app-root',
  imports: [NgOptimizedImage, Reviews],
  template: `
    <h1>The Garden</h1>
    <img ngSrc="/cover.svg" width="300" height="200" priority alt="Cover of The Garden" />
    <p class="story">A gardener finds a door in the old wall.</p>
    @defer (on viewport) {
      <app-reviews />
    } @placeholder {
      <p>Reviews load when you scroll here.</p>
    } @loading (after 100ms) {
      <p>Loading reviews...</p>
    }
  `,
  styles: `
    .story {
      min-height: 150vh;
    }
  `,
})
export class App {}

150vh is one and a half times the window’s height, so the placeholder starts out of sight. When the page opens, the console is empty:

Press End to jump to the bottom of the page. The page shows:

The Garden
A gardener finds a door in the old wall.
Reviews
Ana: A calm, lovely read.
Ben: Slow start, great ending.

and the console shows:

reviews.ts loaded

The image doesn’t appear in page text, which is why it isn’t listed. Some choices here:

  • The cover is at the top and has priority. The reviews are below and deferred. That’s the usual split: what the user sees first loads first.
  • @loading (after 100ms) shows nothing on a fast connection. On a slow one, the reader sees “Loading reviews…” instead of a placeholder that seems stuck.
  • To have the reviews ready before the reader gets there, add prefetch on idle: @defer (on viewport; prefetch on idle).

Worked example: reading NG8020 and NG0750

Back to the report page, with chart.ts as it was in “Try this first”. Say we want some text next to the Show chart button, in the placeholder:

// src/app/chart.ts
import { Component } from '@angular/core';

console.log('chart.ts loaded');

@Component({
  selector: 'app-chart',
  template: `<p>Sales: ▇▇▇▅▂</p>`,
})
export class Chart {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Chart } from './chart';

@Component({
  selector: 'app-root',
  imports: [Chart],
  template: `
    <h1>Report</h1>
    @defer (on interaction) {
      <app-chart />
    } @placeholder {
      <p>The chart is ready when you are.</p>
      <button>Show chart</button>
    }
  `,
})
export class App {}

The build stops:

✘ [ERROR] NG8020: Trigger with no target can only be placed on an @defer that has a @placeholder block with exactly one root element node [plugin angular-compiler]

Read it piece by piece:

  • “Trigger with no target” is our on interaction with nothing in brackets. It watches the placeholder.
  • “Exactly one root element node” means the placeholder must be one element at the top level. Ours has two, a <p> and a <button>, and Angular can’t tell which one to watch.

There are two fixes. Wrap both in one <div>, so a click anywhere in it counts. Or say which element is the target, with a template reference variable:

// src/app/app.ts
import { Component } from '@angular/core';
import { Chart } from './chart';

@Component({
  selector: 'app-root',
  imports: [Chart],
  template: `
    <h1>Report</h1>
    @defer (on interaction(showButton)) {
      <app-chart />
    } @placeholder {
      <p>The chart is ready when you are.</p>
      <button #showButton>Show chart</button>
    }
  `,
})
export class App {}

Now only the button starts the load. The page shows:

Report
The chart is ready when you are.
Show chart

Click Show chart, and it shows:

Report
Sales: ▇▇▇▅▂

Now the second error. This time chart.ts throws while it loads, as in the @error section, but the block has a @loading and no @error:

// src/app/chart.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-chart',
  template: `<p>Sales: ▇▇▇▅▂</p>`,
})
export class Chart {}

throw new Error('chart.ts failed');
// src/app/app.ts
import { Component } from '@angular/core';
import { Chart } from './chart';

@Component({
  selector: 'app-root',
  imports: [Chart],
  template: `
    <h1>Report</h1>
    @defer (on interaction) {
      <app-chart />
    } @placeholder {
      <button>Show chart</button>
    } @loading {
      <p>Loading chart...</p>
    }
  `,
})
export class App {}

Click Show chart. The page shows this, and stays that way:

Report
Loading chart...

The console has the reason:

ERROR RuntimeError: NG0750: Loading dependencies for `@defer` block failed, but no `@error` block was configured (used in the '_App' component template). Consider using the `@error` block to render an error state.

Angular tried to invoke the following dependency function (compiler-generated):
...
but it resulted in the following error:

chart.ts failed. Find more at https://v22.angular.dev/errors/NG0750
  • NG0750 says loading failed and there was no @error block to show instead.
  • “Used in the ‘_App’ component template” names the component that holds the block. (The _ is added by the build; it’s your App.)
  • The last line is the original error, here our chart.ts failed. In real life it’s often “Failed to fetch dynamically imported module”, the browser’s message when the chunk didn’t arrive.

The fix is an @error block, so the user sees a message instead of a loading text that never ends. Give every @defer that loads real code one.

Best practices

  • Defer what the user doesn’t see first. Charts behind buttons, content far down the page, dialogs. It keeps the first download small. It replaces putting every component in the first download.
  • Don’t defer what’s on screen at load. A block there with on immediate, on timer or on viewport shows its placeholder and then jumps to the content, and the page shifts as it loads. Keep that content in the first download.
  • Add @error to every block that loads code, and @loading (after 100ms) where a load might be slow. The user always sees something true. It replaces a placeholder or loading message that never goes away.
  • Use prefetch when you can guess the user’s next step. on interaction; prefetch on idle shows on the click but downloads before it. It replaces making the user wait for the download after they click.
  • Check the build output for the lazy chunk, and keep a budget. A lazy chunk with your component’s name, and a size that matches the component, shows the split worked. A chunk of a few bytes is only a pointer back into the first download. The budget catches a first download that grows. It replaces guessing.
  • Use NgOptimizedImage for images, with priority on the main image. Development builds then check your width, height and priority for you. It replaces plain <img src> tags with no size.

Tips and traps

  • Testing @defer with plain ng serve. With HMR on, ng serve downloads the code for every @defer block when the page opens and logs NG0751. The placeholders and triggers still work, but your console.log and the Network tab show everything loading at once, and the build output lists no lazy chunk. Run ng serve --no-hmr when you’re checking when code loads.
  • Using a deferred component outside the block. A viewChild(), a second <app-chart> outside @defer, or any use in the class moves it back into the first download. There’s no warning, only a missing lazy chunk. Check ng build.
  • Two elements in a placeholder. on viewport, on interaction and on hover with no target fail with NG8020. Wrap the placeholder in one element, or name a target: on interaction(showButton).
  • Expecting when to hide the block again. Once loaded, a @defer block stays, even if the condition turns false. To show and hide, put the block inside an @if.
  • A missing width or height on ngSrc. The image doesn’t load at all, and the console shows NG02954: ... has detected that these required attributes are missing: "width", "height". Add both, using the image’s real size.
  • A width and height with the wrong shape. If the file is 300 by 200 and you write 300 by 300, the browser draws it 300 by 300, so a photo looks stretched, and the console warns with NG02952, “the aspect ratio of the image does not match the aspect ratio indicated by the width and height attributes”. Use the real size and scale the image with CSS.

@defer moves code out of the first download only when nothing else in the file uses it, so check the build for the lazy chunk.

Exercises

Exercise 1. This page should load the comments only when you click Show comments. But comments.ts loaded is in the console as soon as the page opens, and ng build lists no lazy chunk. Comments is used only inside @defer. Why isn’t it deferred? Fix it.

// src/app/comments.ts
import { Component } from '@angular/core';

console.log('comments.ts loaded');

export const MAX_COMMENTS = 50;

@Component({
  selector: 'app-comments',
  template: `<p>Ana: Great post!</p>`,
})
export class Comments {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Comments, MAX_COMMENTS } from './comments';

@Component({
  selector: 'app-root',
  imports: [Comments],
  template: `
    <h1>Post</h1>
    <p>Up to {{ max }} comments are shown.</p>
    @defer (on interaction) {
      <app-comments />
    } @placeholder {
      <button>Show comments</button>
    }
  `,
})
export class App {
  protected readonly max = MAX_COMMENTS;
}
comments.ts loaded

Exercise 2. A page has a Help button and, under it, a help panel in a @defer block. Make the panel load when the mouse moves over the button, not over the panel’s placeholder. The panel can be a component, help-panel.ts, that shows “Press Tab to move between fields.” and logs help-panel.ts loaded when its file loads.

Exercise 3. Without running it, what does this page show after you click Show notes and then Hide notes? Then change it so Hide notes hides them again.

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="open.set(true)">Show notes</button>
    <button (click)="open.set(false)">Hide notes</button>
    @defer (when open()) {
      <p>Notes: water the roses.</p>
    } @placeholder {
      <p>No notes shown.</p>
    }
  `,
})
export class App {
  protected readonly open = signal(false);
}
Answers

1. The import line that brings Comments also brings MAX_COMMENTS, which the class uses, so the compiler keeps the whole line as a normal import. Splitting it into two import lines doesn’t help either: any eager import from comments.ts makes the browser load that file at startup. Move the constant to a file of its own:

// src/app/comment-limits.ts
export const MAX_COMMENTS = 50;
// src/app/comments.ts
import { Component } from '@angular/core';

console.log('comments.ts loaded');

@Component({
  selector: 'app-comments',
  template: `<p>Ana: Great post!</p>`,
})
export class Comments {}
// src/app/app.ts
import { Component } from '@angular/core';
import { MAX_COMMENTS } from './comment-limits';
import { Comments } from './comments';

@Component({
  selector: 'app-root',
  imports: [Comments],
  template: `
    <h1>Post</h1>
    <p>Up to {{ max }} comments are shown.</p>
    @defer (on interaction) {
      <app-comments />
    } @placeholder {
      <button>Show comments</button>
    }
  `,
})
export class App {
  protected readonly max = MAX_COMMENTS;
}

The console is empty when the page opens:

Click Show comments. The page shows:

Post
Up to 50 comments are shown.
Ana: Great post!

and the console shows:

comments.ts loaded

2. Mark the button with a template reference variable and give it to on hover. on hover also fires when the button gets keyboard focus.

// src/app/help-panel.ts
import { Component } from '@angular/core';

console.log('help-panel.ts loaded');

@Component({
  selector: 'app-help-panel',
  template: `<p>Press Tab to move between fields.</p>`,
})
export class HelpPanel {}
// src/app/app.ts
import { Component } from '@angular/core';
import { HelpPanel } from './help-panel';

@Component({
  selector: 'app-root',
  imports: [HelpPanel],
  template: `
    <button #helpButton>Help</button>
    @defer (on hover(helpButton)) {
      <app-help-panel />
    } @placeholder {
      <p>Help is one step away.</p>
    }
  `,
})
export class App {}

The console is empty at first:

Move the mouse over Help. The page shows:

Help
Press Tab to move between fields.

and the console shows:

help-panel.ts loaded

3. The notes stay. Show notes makes open() true, and the block loads. Hide notes makes it false, but a @defer block never goes back. Here’s the run:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="open.set(true)">Show notes</button>
    <button (click)="open.set(false)">Hide notes</button>
    @defer (when open()) {
      <p>Notes: water the roses.</p>
    } @placeholder {
      <p>No notes shown.</p>
    }
  `,
})
export class App {
  protected readonly open = signal(false);
}
Show notesHide notes
Notes: water the roses.

To show and hide, use @if for showing and hiding, and @defer inside it for loading. on immediate loads the block as soon as the @if has created it and the page has rendered:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="open.set(true)">Show notes</button>
    <button (click)="open.set(false)">Hide notes</button>
    @if (open()) {
      @defer (on immediate) {
        <p>Notes: water the roses.</p>
      }
    } @else {
      <p>No notes shown.</p>
    }
  `,
})
export class App {
  protected readonly open = signal(false);
}

Click Show notes. The page shows:

Show notesHide notes
Notes: water the roses.

Click Hide notes, and it shows:

Show notesHide notes
No notes shown.

What’s next

Deferred content helps the page load fast, but only if everyone can use what loads. In Part 28, we’ll build an accessible listbox, tabs and a menu with @angular/aria, with the keyboard support they need.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.