Week 07 · Day 06 — 動態元件深入:實例控制與銷毀
學習目標
- 管理動態建立的元件實例
- 建立後銷毀以節省資源
- 搭配生命周期安全使用
重點
保存與銷毀實例
export class ContainerComponent implements AfterViewInit, OnDestroy {
@ViewChild('container', { read: ViewContainerRef })
container!: ViewContainerRef;
componentRef!: ComponentRef<AlertComponent>;
ngAfterViewInit(): void {
this.showAlert('Dynamic message');
}
showAlert(msg: string): void {
this.clear();
this.componentRef = this.container.createComponent(AlertComponent);
this.componentRef.instance.message = msg;
}
clear(): void {
this.componentRef?.destroy(); // 銷毀實例
this.componentRef = undefined;
}
ngOnDestroy(): void {
this.clear(); // 元件銷毀時也清掉動態實例
}
}
重點
- 動態建立的元件也要管理生命週期
- 用 componentRef.destroy() 銷毀
- 在宿主元件 ngOnDestroy 一併清理,避免記憶體洩漏
換掉動態內容
- 直接對 componentRef.instance 賦值即可更新顯示
- 或銷毀再重建
何時用哪種
| 情境 | 工具 |
|------|------|
| 依條件切換固定元件 | *ngIf 或 ngComponentOutlet |
| 完全由程式建立/銷毀、多實例 | ViewContainerRef |
實作
- 擴充 Day05 的容器元件,加入
clear()與銷毀 - 在
ngOnDestroy一併清理 - 測試連續 create/destroy 是否正常
作業
- 動態元件建立後能正確銷毀
- 在
ngOnDestroy清理動態實例 - 說出
componentRef.destroy()的用途