Blog>
Snippets

Dynamic Component Loading with NgModules

Provide an example of dynamic component loading using an NgModule, utilizing Angular's ComponentFactoryResolver to load components at runtime.
import { NgModule, Component, ComponentFactoryResolver, ViewChild, ViewContainerRef, ComponentRef, AfterViewInit } from '@angular/core';

// This is our dynamic component we want to load
@Component({
    selector: 'dynamic-component',
    template: '<p>I am a dynamic component</p>'
})
export class DynamicComponent {}

@NgModule({
    declarations: [DynamicComponent],
    entryComponents: [DynamicComponent]
})
export class DynamicComponentModule {}
Define the dynamic component and create an NgModule to declare it.
import { DynamicComponentModule } from './dynamic-component.module';
import { DynamicComponent } from './dynamic.component';

// DynamicContainerComponent will serve as the container for the dynamic components
@Component({
    selector: 'dynamic-container',
    template: '<ng-template #container></ng-template>'
})
export class DynamicContainerComponent implements AfterViewInit {
    @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
    componentRef: ComponentRef<any>;

    constructor(private resolver: ComponentFactoryResolver) {}

    ngAfterViewInit() {
        const factory = this.resolver.resolveComponentFactory(DynamicComponent);
        this.componentRef = this.container.createComponent(factory);
    }

    ngOnDestroy() {
        if (this.componentRef) {
            this.componentRef.destroy();
        }
    }
}
Create a container component where the dynamic component will be loaded using Angular's ComponentFactoryResolver.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { DynamicContainerComponent } from './dynamic-container.component';
import { DynamicComponentModule } from './dynamic-component.module';

@NgModule({
    declarations: [
        DynamicContainerComponent
    ],
    imports: [
        BrowserModule,
        DynamicComponentModule
    ],
    bootstrap: [DynamicContainerComponent]
})
export class AppModule {}
Create the AppModule where we import the DynamicComponentModule and declare our DynamicContainerComponent.