Coding exercise: implement lazy loading in Angular.
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
- Preloading strategies can fetch lazy routes in the background after the first load.
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
- Coding exercise: build a Todo application in Angular.
- Coding exercise: create a search box with debounce in Angular.
- Coding exercise: fetch API data and display it in a table in Angular.
- Coding exercise: implement pagination in Angular.
- Coding exercise: create a login form with validation in Angular.
- Coding exercise: build a parent-child communication example in Angular.