Blog>
Snippets

Dynamic Component Loading to Conserve Resources

Code example showcasing how to dynamically load and unload components as needed in an Angular app, preserving memory and processing resources on mobile devices.
import { Component, OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';

@Component({
  selector: 'app-dynamic-component-loader',
  template: `<ng-template #dynamicComponentContainer></ng-template>`
})
export class DynamicComponentLoaderComponent implements OnInit {
  @ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit(): void { }

  async loadComponent(component: any) {
    // Clears the container
    this.container.clear();

    // Asynchronously imports the component
    const { DynamicComponent } = await import(`./path/to/dynamic/${component}.component`);
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
    this.container.createComponent(componentFactory);
  }

  unloadComponent() {
    // Clears the container to unload the component
    this.container.clear();
  }
}
Defines a DynamicComponentLoaderComponent that provides methods to dynamically load and unload components within a placeholder directive in the template. The loadComponent method dynamically imports a component using Angular's ComponentFactoryResolver and appends it to the ViewContainerRef at runtime. The unloadComponent method clears the container, effectively unloading the component, to conserve resources.