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:
- A/B Testing: experimenting new component implementations on users.
- Canary Release: progressively deploying new components.
- White Labeling: same application with different brandings and features.
- Dynamic Customization: let the user choose the components.
How?
Well, it’s quite simple using @wishtack/reactive-component-loader
.
… and it works with AOT!!!
So, to use it, you just have to:
- Create the modules that will be lazy loaded.
- Add the lazy loaded components to
entryComponents
. - Declare the lazy loaded modules using
ReactiveComponentLoaderModule.withModule(...)
and choose a unique module id. - Inject the component wherever and whenever you want using
wt-lazy
component.
<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: