0
0
Angularframework~5 mins

Dynamic component loading in Angular

Choose your learning style9 modes available
Introduction

Dynamic component loading lets you add components to your app while it is running. This helps show different content without rebuilding the whole page.

You want to show different widgets based on user choices.
You need to load a popup or modal only when needed.
You want to reduce initial load by loading parts later.
You want to create a dashboard with user-selected panels.
Syntax
Angular
import { Component, ViewContainerRef, ComponentRef, inject } from '@angular/core';

@Component({
  selector: 'app-dynamic-loader',
  template: `<ng-template #container></ng-template>`,
  standalone: true
})
export class DynamicLoaderComponent {
  private viewContainerRef = inject(ViewContainerRef);

  loadComponent(component: any): ComponentRef<any> {
    this.viewContainerRef.clear();
    return this.viewContainerRef.createComponent(component);
  }
}

Use ViewContainerRef to control where the component appears.

Call createComponent() to add the component dynamically.

Examples
Loads MyComponent inside the container.
Angular
this.viewContainerRef.createComponent(MyComponent);
Removes previous components before loading AnotherComponent.
Angular
this.viewContainerRef.clear();
this.viewContainerRef.createComponent(AnotherComponent);
Loads MyComponent and sets an input property.
Angular
const compRef = this.viewContainerRef.createComponent(MyComponent);
compRef.instance.someInput = 'Hello';
Sample Program

This example shows a button that loads a simple component dynamically inside the page when clicked.

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

@Component({
  selector: 'app-hello',
  template: `<p>Hello, I am a dynamic component!</p>`,
  standalone: true
})
export class HelloComponent {}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="loadHello()">Load Hello Component</button>
    <ng-template #container></ng-template>
  `,
  standalone: true
})
export class AppComponent {
  private viewContainerRef = inject(ViewContainerRef);

  loadHello() {
    this.viewContainerRef.clear();
    this.viewContainerRef.createComponent(HelloComponent);
  }
}
OutputSuccess
Important Notes

Always clear the container before loading a new component to avoid stacking.

You can pass data to the dynamic component by setting properties on compRef.instance.

Dynamic loading helps keep your app fast by loading only what is needed.

Summary

Dynamic component loading lets you add components while the app runs.

Use ViewContainerRef and createComponent() to load components.

This technique is useful for popups, dashboards, and conditional content.