首页 > 解决方案 > 如何在 Angular 的 ts 文件中销毁动态加载的组件?

问题描述

我创建了一个动态组件加载器,它工作正常,但我将如何销毁其 ts.file 中的组件?

动态加载的组件:

<button class="btn btn-secondary" (click)="destroyComp()"> Destroy</button>

问题是,函数的实现destroyComp会是什么样子?有没有我可以调用的函数,以便组件在不做任何事情的情况下自行销毁?

这将是工作正常的组件加载器(在应用程序组件中):

popups = [
    {id:1, component: TestComponent}
  ]
@ViewChild('popup', {read: ViewContainerRef}) public popup: ViewContainerRef;

loadPopupComponent(i: number, event){
    if(i == 0 || !this.popup) return;
    const component = this.popups.find(x => x.id == i).component;
    if(component){
      const target = this.popup;
      const widgetComponent = this.componentFactoryResolver.resolveComponentFactory(component);
      let cmpRef: ComponentRef<any> = target.createComponent(widgetComponent);
    }
  }

和 HTML 文件

<ng-template #popup></ng-template>

标签: angulartypescriptcomponents

解决方案


ComponentRef有一个destroy()方法,就像从 DOM 中删除组件一样

销毁组件实例以及与之关联的所有数据结构。

cmpRef.destroy()


推荐阅读