Week 07 · Day 05 — 動態元件:ngComponentOutlet 與 ViewContainerRef
學習目標
- 用
ngComponentOutlet動態載入元件 - 用
ViewContainerRef.createComponent程式化建立元件 - 理解「靜態宣告 vs 動態建立」
重點
ngComponentOutlet:在模板動態指定要顯示的元件
@Component({
selector: 'app-dynamic',
template: `
<ng-container *ngComponentOutlet="currentComponent"></ng-container>
`
})
export class DynamicComponent {
currentComponent = AlertComponent; // 類別,而非實例
}
currentComponent 指定「哪個元件類別」
- 切換 currentComponent 畫面就跟著換
ViewContainerRef:程式化建立
import { ViewChild, ViewContainerRef, Component, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-container',
template: `<div #container></div>`
})
export class ContainerComponent implements AfterViewInit {
@ViewChild('container', { read: ViewContainerRef })
container!: ViewContainerRef;
ngAfterViewInit(): void {
const componentRef = this.container.createComponent(AlertComponent);
componentRef.instance.message = "Dynamic component!";
}
}
關鍵點
- { read: ViewContainerRef }:從 #container 讀取「容器」而非 Element
- createComponent(AlertComponent):建立實例
- componentRef.instance:存取該元件實例,設定屬性
實作
- 用
ngComponentOutlet建立可切換的動態元件 - 用
ViewContainerRef.createComponent程式化建立AlertComponent - 設定
instance.message並確認顯示
作業
- 用
*ngComponentOutlet動態顯示元件 - 用
ViewContainerRef程式化建立元件 - 說明
componentRef.instance的作用