如何以角度动态删除组件 [英] How to remove a component dynamically in angular
问题描述
我经历了 Angular 动态加载组件.但是我找不到如何动态删除组件.
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屋!