I’m creating components dynamic using a service. Component was created, but the ngOnDestroy
lifecycle look is not getting called.
Below is my service file code.
@Injectable()
export class CreateComponentService implements OnDestroy {
private rootViewContainer: ViewContainerRef;
private componentFactory: ComponentFactory<any>;
private componentReference;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
setRootViewContainerRef(view: ViewContainerRef): void {
this.rootViewContainer = view;
}
createComponent(content, type) {
this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
this.componentReference = this.rootViewContainer.createComponent(this.componentFactory);
this.componentReference.instance.contentOnCreate(content);
}
ngOnDestroy() {
// Destroy components to avoide memory leaks
this.componentReference.destroy();
}
}
In Component.ts
constructor(private service: CreateComponentService) {}
data.forEach(response => {
this.service.createComponent(response, type);
});
Please show me the best way to destroy the component instance