(angular 8 in use)
I have an issue currently with my code using a behaviour subject.
Component A creates another component B trough the component factory. Now, Component A subscribes to component B it's status to know when to delete it. In this case, whenever there is an error in component B, Component A will change its own status and call Component B.destroy().
However, whenever I will run this destory method, I get an error in the logs saying
ERROR Error: ViewDestroyedError: Attempt to use a destroyed view: detectChanges
I do untach the change detector before i'm removing it, but that does not seem to help.
Here is the code:
createComponent(): void {
this.logger.debug('Widget: creating component based on type provided in config.');
this.setWidgetLoading(true);
this.componentFactory.createComponent(this.content, this.componentConfig).subscribe((componentRef) => {
this.componentRef = componentRef;
this.componentRef.instance.componentStatus.subscribe((status: Status) => {
this.setComponentStatus(status);
});
}, (error: Error) => {
this.setComponentStatus(StatusFactory.createErrorStatus(error));
this.setWidgetLoading(false);
},
() => {
this.setWidgetLoading(false);
this.logger.debug('Widget: component created based on type provided in config.');
});
}
setComponentStatus(status: Status): void {
case STATUS_TYPE.ERROR:
this.setWidgetLoading(false);
this.componentRef.changeDetectorRef.detach();
this.componentRef.destroy(); //componentRef references the created component B
return;
}
EDIT
here are the two methods from component B
ngAfterViewChecked(): void {
if (this.config.mode === ENTITY_FORM_MODE.UPDATE && !this.data) {
this.logger.debug('EntityCreationComponent: initialized for update mode but no data provided.');
this.setErrorStatus(ErrorFactory.createError('initialized for update mode but no data provided.'));
}
}
ngOnInit() {
super.ngOnInit();
this.entity = Object.assign(this.entity ? this.entity : {}, EntityFactory.createEntity(this.config.dataConfig.dataType));
this.logger.debug('EntityCreationComponent: initialized.');
}