【问题标题】:How to destroy a dynamically loaded component within its ts-file in Angular?如何在 Angular 的 ts 文件中销毁动态加载的组件?
【发布时间】:2021-01-11 13:28:29
【问题描述】:

我创建了一个动态组件加载器,它工作正常,但我将如何销毁其 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>

【问题讨论】:

    标签: angular typescript components


    【解决方案1】:

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

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

    cmpRef.destroy()

    【讨论】:

    • 感谢您的回答。问题是,cmpRef 在另一个组件中。但是我想在单击同一组件中的按钮时销毁该组件。我不想存储 ComponentRef,这就是为什么我想在 destroyComp()function 的帮助下将组件销毁在它自己的 ts 文件中,但我不知道如何实现该函数
    • @CNIS 您可以在创建服务时将cmpRef 存储在服务中,这样您就可以从另一个组件访问它并在其上调用destroy()
    • @CNIS 刚刚看到编辑,不幸的是,您必须将引用存储在某个地方才能访问它,或者当父组件(如果有)被销毁时,其子组件也将被销毁为好
    • 哦,谢谢,我会把变量存储在某个地方。
    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2019-07-28
    • 2019-02-18
    • 1970-01-01
    • 2019-11-11
    • 2015-07-26
    相关资源
    最近更新 更多