Fahrradmobilität am Kanal
Dennis, Kiya | 14.08.2023

Lazy Loading of Components without Router Modules

Webentwicklung > 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.

Inhalt
  • 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)

Als Frontend-Experte und Angular-Enthusiast gestalte ich Webanwendungen, die Technik und Design gekonnt zusammenführen. Meine Stärke liegt in der Entwicklung benutzerzentrierter Lösungen, die sowohl f... 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

More about this topic

More from Dennis

Unsere Entwicklungsexpertise

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund