从服务创建后销毁组件实例

时间:2019-03-21 09:29:48

标签: angular angular-dynamic-components

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

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

添加了一个stackBlitz项目以供参考

https://stackblitz.com/edit/dynamic-component-example-5o8pz8

1 个答案:

答案 0 :(得分:0)

您不会显式销毁服务,并且不会调用服务的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最终将被垃圾回收。而且由于分离了视图,所以它的行为就像静态内容一样。请注意,如果您销毁containerRef,则关联的view / html也将被销毁。

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