Thuta Learning
AdvancedWeb Developmentintermediate

Dynamic Components

Relax. We'll talk through this in plain words — no textbook voice.

Dynamic Components can be created programmatically at runtime.

typescript
// dynamic-host.directive.ts
import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appDynamicHost]'
})
export class DynamicHostDirective {
  constructor(public viewContainerRef: ViewContainerRef) {}
}

// parent.component.ts
import { ComponentFactoryResolver, ViewChild } from '@angular/core';

export class ParentComponent {
  @ViewChild(DynamicHostDirective, { static: true }) 
  dynamicHost!: DynamicHostDirective;
  
  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
  
  loadComponent() {
    const viewContainerRef = this.dynamicHost.viewContainerRef;
    viewContainerRef.clear();
    
    const componentRef = viewContainerRef.createComponent(AlertComponent);
    componentRef.instance.message = 'Dynamic Alert!';
  }
}

// parent.component.html
<div appDynamicHost></div>
<button (click)="loadComponent()">Load Component</button>
You should see
(Clicking the button will dynamically create AlertComponent at runtime)
Dynamic Components | Thuta Learning