Angular Lazy Loading (Example)

Angular Lazy Loading

Example

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)

Related Post

FREE ePub Quicklook and Spotlight Plugins for Mac ... When you have a lot of ePub books, it can be useful to see excerpt and meta data information in quicklook. Even more important...
FAQ: Mac OS X Services HEIC to JPG on Right-Click Service Q: Where’d all my services go? I don’t see anything in the Services menu. A: If you don’t select anything before...
Right-Click to Translate (Look Up) with Google Tra... If you are not native english speaker, you may be frustrated with default "look up" options you get after selecting a text and right clicking. There a...
Translate Selected Text to English on Right Click ... TL;DR; Need instant translation right in context menu? You can accomplish it for free with one line of code in Automator, or you can proc...
PPTP VPN on MAC OS X Sierra, High Sierra and Mojav... PPTP VPN for Mac OS X Introduction PPTP VPN is no longer supported on macOS Sierra and High Sierra and that is just fine, because there are some se...
Free Better Battery Stats and Time Remaining for M... Better Battery Stats and Time Remaining for Mac OS TL;DR; Do you miss the time remaining indicator on your MacBook, MacBook Air, or MacBook Pro? He...
Buy me a coffeeOut of coffee 😱, please help!