Angular Lazy Loading (Example)

Angular Lazy Loading


Angular routing is undoubtedly one of the most hated api. It’s shrouded in mystery and it requires a lot of patience to learn it. In this example I will show you how to accomplish Angular lazy loading. Let’s say we have two components (named classic.component.ts and lazy.component.ts) and we want to load the second one on demand.

How Does It Work

We will be creating very simple app, with structure like this:

├── index.html
├── app
    ├── app.component.ts
    ├── app.module.ts
    ├── app.routing.ts
    ├── main.ts
    ├── classic.component.ts
    └── lazy
        ├── lazy.component.ts
        ├── lazy.module.ts
        └── lazy.routing.ts

First of all, you can’t lazy load just component. You have to lazy load whole module so we need to create out lazy.module.ts:

and its lazy.component.ts:

and lazy.routing.ts:

Now we can create our routing.module.ts and do all the magic with loadChildren route and #LazyModule postfix in one of our routes:

In app.component.ts don’t forgot to include router-outlet and routerLinks in menu items:

And that’s it!

Multiple Named Outlets

If are you asking if it’s possible to have multiple named outlets with lazy loaded modules, it’s not yet. You can watch this GitHub issue for updates: (Named lazy loaded outlets issue)

Buy me a coffeeBuy me a coffee