Component switching dynamically using lazy loading in Angular templates

Why should we load the chunk for a component that we will not render at runtime or would it make more sense to load the component chunk having the huge size to load on request and not include it in the initial load, optimizing the initial load time as well?

Ankit kaushik
2 min readMar 7, 2023
Photo by Jonas Leupe on Unsplash

Suppose we want to implement something like this:

<ng-container [ngSwitch]="active">
<app-first *ngSwitchCase="'first'"></app-first>
<app-second *ngSwitchCase="'second'"></app-second>
<app-third *ngSwitchCase="'third'"></app-third>
<app-fourth *ngSwitchCase="'fourth'"></app-fourth>
</ng-container>

Based on the value held inside the variable active, we need to render only one of the components shown, or you just want to postpone the loading of a component until render.

What if we keep a map where these references are held lazily

componentMap = {
first: defer(() => import('./first.component').then(m => m.default)),
second: defer(() => import('./second.component').then(m => m.default)),
third: defer(() => import('./third.component').then(m => m.default)),
fourth: defer(() => import('./fourth.component').then(m => m.default)),
}

In case you are wondering, why did we use defer here? It will not invoke the callback function passed until the subscription. In our case, it won’t import or load the component file or class until we request that in our templates. Now, we could simply update our template to accommodate this strategy:

<ng-container *ngComponentOutlet="componentMap[active] | async"></ng-container>

You can simply use this trick to make any Eagar component in your template lazy load at runtime. For demonstration purposes, I’ve assumed that you are doing it on your standalone components but ngComponentOutlet has an input to accommodate the parent module too (Not to mention, that you wouldn’t want to refer to static or eager imports to load your modules as well). You could do a lot more with this directive, for reference: https://angular.io/api/common/NgComponentOutlet

I condemn this approach for your presentation components. Instead, you could use it for your container components representing any business entity segment.

--

--