如何动态删除角度组件 [英] How to remove a component dynamically in angular

查看:92
本文介绍了如何动态删除角度组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历了角度动态加载组件.但是我找不到如何动态删除组件.

I went through angular dynamically loading components. But i could not find how to remove the component dynamically.

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

My requirement is that the chat application loads dynamic component(image/graph/list/table) as per the conversation. But how can i destroy the component if the conversation moves forward.

我正在尝试通过外部事件破坏动态组件.

I am trying to destroy dynamic component with external event.

请帮助进行操作.

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

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

I developed my code according to this example. Instead of time interval, I need to use a API call from a service that is subscribed another component(chat component).

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

Below API response can load the component.I am looking for how to destroy the already loaded component i use the API call again.

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');
  }

推荐答案

使用destroy()方法

Use destroy() method

销毁组件实例和所有数据结构 与之关联.

Destroys the component instance and all of the data structures associated with it.

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

这篇关于如何动态删除角度组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆