首页 > 解决方案 > 从服务创建后销毁组件实例

问题描述

我正在使用服务创建动态组件。组件已创建,但未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);
      });

请告诉我销毁组件实例的最佳方法

标签: angularangular-dynamic-components

解决方案


您没有显式销毁服务,并且不会调用服务 onDestroy 方法。

您可以尝试从更改检测树中分离视图,这与您需要的类似,

private insertComponent(componentType): void {
    const factory = this.factoryResolver.resolveComponentFactory(componentType);
    var containerRef = this.rootViewContainer.createComponent(factory);
    // always get the most recently appended node
    var viewRef = this.rootViewContainer.get(this.rootViewContainer.length - 1);
    viewRef.detach();
    containerRef = null;
}

containerRef最终将被垃圾收集。而且由于您分离了视图,它的行为就像静态内容一样。请注意,如果您 destroy containerRef,关联的 view/html 也将被销毁。

更新:演示https://stackblitz.com/edit/dynamic-component-example-swrj8j?file=src/app/service-based/factory.service.ts


推荐阅读