Dynamic Components များကို runtime တွင် programmatically create လုပ်နိုင်သည်။
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
(Button ကိုနှိပ်လျှင် AlertComponent သည် runtime တွင် dynamically create ဖြစ်မည်)