This post describes how to implement lazy or dynamic component loading with angular, based on an Angular 10 demo implementation.

In Angular applications, it is sometimes necessary to load components dynamic/lazy and asynchronous at runtime. Just think of loading captcha, promotion, or advertisement components.
Manual component loading with Angular is achieved very easily once you have seen an example implementation, and that’s what I provide.

Assume an existing Angular application or at least a component (AppComponent) needs to be extended by an existing component (DynamicComponent), which should be loaded lazy, async at runtime.

1. Add an HTML-Container

Start the implementation by adding an HTML-Container.

...  
<div>
  <ng-container #dynamicContainer></ng-container>
</div>
...

And create a container reference to the associated Angular component.

export class AppComponent {
 
  @ViewChild('dynamicContainer', {read: ViewContainerRef})
  dynamicContainer: ViewContainerRef;
  
  ...
}

2. Lazy Load Angular Component

The ViewContainterRef provides a method called createComponent() that uses a ComponentFactory to create and inject a new component.
A ComponentFactory of a given type can be retrieved using the Angular ComponentFactoryResolver.

Do not forget to store the reference of the new component created, which is needed, for example, to manually destroy the component.

import {Component, ComponentFactoryResolver, ComponentRef, Injector, ViewChild, ViewContainerRef} from '@angular/core';
...
export class AppComponent {
  
  @ViewChild('dynamicContainer', {read: ViewContainerRef})
  dynamicContainer: ViewContainerRef;

  private _dynamicInstance: ComponentRef<DynamicComponent>;

  constructor(private componentFactoryResolver: ComponentFactoryResolver,
              private injector: Injector) { }

  async loadComponentAsync() {
    const {DynamicComponent} = 
      await import('./components/dynamic/dynamic.component');
    
    // create component factory for DynamicComponent
    const dynamicComponentFactory = 
      this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
    
    // create and inject component into dynamicContainer
    this._dynamicInstance = 
      this.dynamicContainer.createComponent(dynamicComponentFactory, null, this.injector);
  }

}

3. Destroy Lazy Loaded Component

The dynamic and manually created component can be destroyed using the stored component reference.

this._dynamicInstance.destroy();

Categories: Engineering

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *