【发布时间】:2020-06-08 13:18:22
【问题描述】:
const validReportTemplates = {
default: DefaultTemplateComponent
}
@ViewChild('container', { read: ViewContainerRef }) containerRef: ViewContainerRef;
private _componentRef: ComponentRef<any>;
constructor(
public activeModal: NgbActiveModal,
private _notificationsService: NotificationsService,
private _componentFactoryResolver: ComponentFactoryResolver,
private _inspectionService: InspectionService,
private _reportService: ReportService
) {}
ngAfterViewInit (): void {
this._loadReportTemplate();
}
private _loadReportTemplate() {
const inspection: Inspection = this._inspectionService.inspectionForm.value;
this.containerRef.clear();
const factory = this._componentFactoryResolver.resolveComponentFactory<any>(validReportTemplates['default']);
this._componentRef = this.containerRef.createComponent(factory);
}
ngOnDestroy(): void {
this._componentRef.destroy();
this.containerRef.clear();
}
}
DefaultTemplateComponent 中的 ngOnDestroy() 生命周期钩子无论如何都会被触发。如果我在父母 onDestroy 钩子中调用 destroy() 和 clear() 并不重要。那么真的有必要手动执行吗?
另一个有趣的事实是,当在 ngOnDestroy 钩子中注册超时时,对动态加载的组件的引用在销毁后存在。有什么想法吗?
ngOnDestroy(): void {
this._componentRef.destroy();
this.containerRef.clear();
setTimeout(() => console.log(this._componentRef), 3000); // shows that DefaultTemplateComponent still exists
}
【问题讨论】:
-
没有。正如您所说,当从 DOM 中删除元素时,angular 会为您完成工作并销毁所有组件。您需要做的是在
ngOnDestroy()期间取消订阅任何自定义可观察对象,否则可能导致内存泄漏。 -
@MikeS。谢谢你给的信息。但是为什么超时时仍然引用了已经销毁的组件呢?
标签: angular