Home > Blockchain >  Angular 12 Lazy Load Component Dynamically code doing nothing
Angular 12 Lazy Load Component Dynamically code doing nothing

Time:09-29

I am trying to lazy load a component dynamically with angular 12 but I get no errors and the component does not appear either.

Here is the code:

app.component.ts

import {Component,ViewContainerRef,ComponentFactoryResolver } from '@angular/core';

...

constructor(private vcRef: ViewContainerRef, private cResolver: ComponentFactoryResolver) { }

and the method:

async load() {
    this.vcRef.clear();
    const { MyModalComponent } = await import('../my-modal.component');
    this.vcRef.createComponent(this.cResolver.resolveComponentFactory(MyModalComponent));
  }

app.component.html

<button (click)="load()">Load it</button>

The html in MyModalComponent is just

<p>Component Here</p>

What I'm I missing or what I'm I doing wrong here?

CodePudding user response:

You are creating the component dynamically, but that's all. You also need to add the component the the Angular Component tree and the DOM:

async load {
    const { MyModalComponent } = await import('../my-modal.component');
    // 1. Create a component reference
    const componentRef = this.componentFactoryResolver
      .resolveComponentFactory<MyModalComponent>(component)
      .create(this.injector);

    // 2. Attach component to the appRef so that it's inside the ng component tree
    this.appRef.attachView(componentRef.hostView);

    // 3. Get DOM element from the component
    const domElement = (componentRef.hostView as EmbeddedViewRef<any>)
      .rootNodes[0] as HTMLElement;

    // 4. Append DOM element to the body
    document.body.appendChild(domElement);
}
  • Related