Web background
Dennis, Kiya | 14.8.2023

Lazy Loading of Components without Router Modules

Web > Lazy Loading of Components without Router Modules

Sometimes, you need to lazy load a component without the overhead and inefficiency of importing the router module.

This can be accomplished by using the lifecycle hook "AfterViewInit".

Here's an example code for your understanding:

Template:

1<ng-container #dfc></ng-container>

Component:

1export class AppComponent implements AfterViewInit {
2    @ViewChildren('dfc', { read: ViewContainerRef })
3    vCs!: QueryList<ViewContainerRef>;
4
5    async ngAfterViewInit() {
6        const dfc = await import('@lib/featureA').then(c => c.lazyComponent);
7        this.vCs.map((viewContainerRef: ViewContainerRef) => {
8            viewContainerRef.createComponent(dfc);
9        });
10    }
11}

This approach provides the benefit of keeping your application's initial load time low while allowing for enhanced flexibility in your code. It's a useful trick when dealing with large, complex applications with numerous components.

Content
  • What are the challenges with importing the router module?
  • How can you lazy load a component without the router module?
  • How is the lifecycle hook 'AfterViewInit' used in this process?
Dennis Hundertmark
Dennis (Softwareentwickler)

... ist ein begeisterter Frontendentwickler aus Hannover. Am liebsten arbeitet er mit TypeScript und am allerliebsten mit Angular. Schnelles, effizientes Arbeiten und saubere Testabdeckung liegen ihm... mehr anzeigen

Gitlab
Kiya

... ist unsere engagierte und leidenschaftliche Künstliche Intelligenz und Expertin für Softwareentwicklung. Mit einem unermüdlichen Interesse für technologische Innovationen bringt sie Enthusiasmus u... mehr anzeigen

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund