[英]Angular: destroy dynamic component
在一个聊天应用程序上,我正在使用它来创建多个ChatComponent(作为动态组件)。
loader.service.ts
import { ChatComponent } from '../components/shared/chat/chat.component';
@Injectable()
export class LoaderService {
constructor( @Inject(ComponentFactoryResolver) factoryResolver )
{
this.factoryResolver = factoryResolver
}
setRootViewContainerRef(viewContainerRef){
this.rootViewContainer = viewContainerRef
}
addDynamicComponent(timeIdentifier){
const factory = this.factoryResolver.resolveComponentFactory(ChatComponent);
const component = factory.create(this.rootViewContainer.parentInjector)
component.instance.timeIdentifier = timeIdentifier;
this.rootViewContainer.insert(component.hostView)
}
}
chat-container.component.ts
export class ChatContainerComponent implements OnInit {
@ViewChild('chat', { read: ViewContainerRef }) viewContainerRef: ViewContainerRef
constructor( protected loaderService: LoaderService, protected route: ActivatedRoute ) { }
ngOnInit() {
this.route.params.subscribe(params => {
this.loaderService.setRootViewContainerRef(this.viewContainerRef)
this.loaderService.addDynamicComponent(params['timeIdentifier'])
});
}
}
这样,我可以生成多个“ ChatComponent”作为动态组件。
但是一旦创建它们,我如何销毁它们呢?
编辑
我已经在ChatComponent中添加了此内容(由组件工厂创建)
this.cmpRef.destroy();
但是当我打电话给我时,我陷入了无限循环,出现了如下错误:
ERROR RangeError: Maximum call stack size exceeded
从工厂创建的组件的类型为ComponentRef
。 此类具有destroy
功能,可以销毁实例和关联的结构。
在此处检查: https : //angular.io/api/core/ComponentRef
我找到了销毁组件的更好方法,您可以执行以下操作:
addDynamicComponent(timeIdentifier){
const factory = this.factoryResolver.resolveComponentFactory(ChatComponent);
const component = factory.create(this.rootViewContainer.parentInjector)
component.instance.timeIdentifier = timeIdentifier;
component.instance.autodestroy = () => component.destroy();
this.rootViewContainer.insert(component.hostView)
}
在组件类中,您将创建一个方法autodestroy
,并在您想要销毁它时调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.