Coding exercise: implement lazy loading in Angular.

Angular practical coding · Freshers and experienced

Model answer

Lazy load routes with loadComponent or loadChildren so their code is a separate file downloaded on first visit. For parts of a template use @defer, and for images use the native loading attribute or NgOptimizedImage.

// app.routes.ts
export const routes: Routes = [
  { path: '', component: Home },
  { path: 'admin', loadComponent: () => import('./admin/admin').then((m) => m.Admin) },
  { path: 'shop', loadChildren: () => import('./shop/shop.routes').then((m) => m.SHOP_ROUTES) },
];

In a template, @defer loads a heavy part only when it scrolls into view:

@defer (on viewport) {
  <app-big-chart />
} @placeholder {
  <p>Chart will load…</p>
} @loading {
  <p>Loading…</p>
}

Check the result in the build output: lazy chunks appear as separate files. Do not defer anything visible at first paint.

Tips

Practise it yourself in the React and Angular code playground.

Learn this topic

Angular Tutorial: Beginner to Advanced .

Sign in to add your own answer.

More questions