gpt4 book ai didi

angular - 如何以 Angular 动态删除组件

转载 作者:太空狗 更新时间:2023-10-29 17:33:22 25 4
gpt4 key购买 nike

我经历了 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');
}

最佳答案

使用destroy()方法

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

关于angular - 如何以 Angular 动态删除组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52354312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com