我经历了angular动态加载组件的过程。但我找不到如何动态删除组件。
我的要求是聊天应用程序根据对话加载动态组件(图像/图形/列表/表格)。但是,如果对话继续进行,我如何销毁组件。
我正在尝试用外部事件销毁动态组件。
请帮助了解如何继续操作。
编辑: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');
}
发布于 2018-09-16 21:14:10
使用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
https://stackoverflow.com/questions/52354312
复制相似问题