Angular Lazy Loading without Router

Younes
Younes
Mar 6, 2019 · 2 min read

Let your components decide when to (lazy)load their children!

Lazy loading is a key performance optimization feature in Angular.
In few words, lazy loading will allow your application to start faster by only loading the modules which are required by the view (or route) you are visiting.

One of the main limitations of Angular’s lazy loading is that it is quite coupled to the router but in some specific use cases you might want to lazy load components imperatively without changing the route.

Why?

Dynamic Component Injection

You might have some heavy components that you only display in some conditions.
E.g. : a component on Medium.com that shows some stats but that would only be displayed for the author.

Interchangeable Components

You might have different implementations of a component. They would serve the same purpose and share one signature which is defined by theirInputs & Outputs (Cf. example below).

<med-story-list [stories]="stories" (storySelect)="...">
<med-story-grid [stories]="stories" (storySelect)="...">

Interchangeable components can be used for:

How?

Well, it’s quite simple using @wishtack/reactive-component-loader.

… and it works with AOT!!!

So, to use it, you just have to:

<wt-lazy
[location]="{moduleId: ..., selector: ...}"
[inputs]="..."
[outputs]="...">

Example Source Code

AngularConnect Talk

You can find more detail about interchangeable components and lazy loading on this video:

… and the slides are here:

Marmicode

At Marmicode, we use our passion and experience in Web…

Marmicode

At Marmicode, we use our passion and experience in Web Development & eXtreme Programming to help you cook better apps, ship them fast and make you proud of your work. #javascript #python #angular #continuousdeployment

Younes

Written by

Younes

Google Developer Expert for Angular & Web Technologies | eXtreme Programming Coach | Tech Advisor

Marmicode

At Marmicode, we use our passion and experience in Web Development & eXtreme Programming to help you cook better apps, ship them fast and make you proud of your work. #javascript #python #angular #continuousdeployment

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store