簡體   English   中英

從服務創建后銷毀組件實例

[英]Destroy component instance once created from service

我正在使用服務創建動態組件。 已創建組件,但未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);
      });

請告訴我銷毀組件實例的最佳方法

您沒有顯式銷毀該服務,並且不會調用服務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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM