我正在使用服务创建动态组件。组件已创建,但未ngOnDestroy
调用生命周期外观。
下面是我的服务文件代码。
@Injectable()
export class CreateComponentService implements OnDestroy {
private rootViewContainer: ViewContainerRef;
private componentFactory: ComponentFactory<any>;
private componentReference;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
setRootViewContainerRef(view: ViewContainerRef): void {
this.rootViewContainer = view;
}
createComponent(content, type) {
this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
this.componentReference = this.rootViewContainer.createComponent(this.componentFactory);
this.componentReference.instance.contentOnCreate(content);
}
ngOnDestroy() {
// Destroy components to avoide memory leaks
this.componentReference.destroy();
}
}
在 Component.ts
constructor(private service: CreateComponentService) {}
data.forEach(response => {
this.service.createComponent(response, type);
});
请告诉我销毁组件实例的最佳方法