简体   繁体   English

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

[英]Destroy component instance once created from service

I'm creating components dynamic using a service. 我正在使用服务创建动态组件。 Component was created, but the ngOnDestroy lifecycle look is not getting called. 已创建组件,但未ngOnDestroy生命周期外观。

Below is my service file code. 以下是我的服务文件代码。

@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();
  }
}

In Component.ts 在Component.ts中

constructor(private service: CreateComponentService) {}

      data.forEach(response => {
        this.service.createComponent(response, type);
      });

Please show me the best way to destroy the component instance 请告诉我销毁组件实例的最佳方法

You don't explicitly destroy the service, and the service onDestroy method won't be called. 您没有显式销毁该服务,并且不会调用服务onDestroy方法。

You can try to detach the views from the change-detection tree, which is similar to what you need, 您可以尝试从更改检测树中分离视图,这与您需要的类似,

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 will be garbage collected eventually. containerRef最终将被垃圾收集。 And since you detach the view, it will behave like static content. 并且由于您分离视图,它将表现得像静态内容。 Note that if you destroy containerRef , the associated view/html will also get destroyed. 请注意,如果销毁containerRef ,关联的view / html也将被销毁。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM