【问题标题】:How to remove a component dynamically in angular如何以角度动态删除组件
【发布时间】:2019-02-20 14:03:19
【问题描述】:

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

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

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

请帮助如何进行。

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

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

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

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

【问题讨论】:

  • 请提供一些代码,以便我们追溯您的步骤。

标签: angular angular-components angular-dynamic-components


【解决方案1】:

使用destroy()方法

销毁组件实例和所有数据结构 相关联。

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

【讨论】:

  • 什么时候调用这个方法?它仅在组件退出时才起作用。如果组件不退出 ref.destroy() 则显示错误。我尝试使用以下代码..但它没有用。 if(this.ref!=null){this.ref.destroy();}
  • 没有组件为什么要销毁
  • 如果没有组件..它不应该执行该行..我无法将 if 条件放在那里。当我使用 console.log() 时 this.ref 显示未定义。请帮忙看看 if 条件..,它显示 undefined..
  • 而不是 if 使用 try catch
猜你喜欢
  • 2021-12-15
  • 2021-01-17
  • 2018-05-17
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 2018-08-11
  • 2019-07-11
  • 1970-01-01
相关资源
最近更新 更多