首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在angular中动态删除组件

如何在angular中动态删除组件
EN

Stack Overflow用户
提问于 2018-09-16 20:50:32
回答 1查看 16.8K关注 0票数 5

我经历了angular动态加载组件的过程。但我找不到如何动态删除组件。

我的要求是聊天应用程序根据对话加载动态组件(图像/图形/列表/表格)。但是,如果对话继续进行,我如何销毁组件。

我正在尝试用外部事件销毁动态组件。

请帮助了解如何继续操作。

编辑:https://stackblitz.com/angular/emjkxxxdxmk?file=src%2Fapp%2Fad-banner.component.ts

我根据这个例子开发了我的代码。我需要使用来自订阅了另一个组件(聊天组件)的服务的API调用,而不是使用时间间隔。

下面的API响应可以加载组件。我正在寻找如何销毁已经加载的组件,我再次使用API调用。

代码语言:javascript
复制
public sendMessage(data): void {
    this.messages.push(this.message);
    this.API.getResponse(data).subscribe(res => {
      this.previousContext = res.context;
      console.log('res', res);
      if (res.result.type == 'table') {
        this.DataService.setTrigger(new AdItem(Table2Component, res));
      }
      this.messages.push(
        new Message(res.text, 'assets/images/bot.png', new Date(), 'chatbot')
      );
    });
    this.message = new Message('', 'assets/images/user.png', this.message.timestamp, 'user');
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-16 21:14:10

使用destroy()方法

将销毁组件实例和与其关联的所有数据结构。

代码语言:javascript
复制
ref:ComponentRef<any>;
loadComponent() {
    this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
    let adItem = this.ads[this.currentAdIndex];

    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    let viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();

    let componentRef = viewContainerRef.createComponent(componentFactory);
    this.ref=componentRef;
    (<AdComponent>componentRef.instance).data = adItem.data;

  }

  removeComponent(){
   try{
       this.ref.destroy();
   }
   catch(e){
   }
  }

示例:https://stackblitz.com/edit/destroy?file=src/app/ad-banner.component.ts

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52354312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档