I am dynamically inserting Angular components using renderer2 and elementRef. While that works, I have a problem that upon removing the component (either by removing the parent component, or by calling removeChild on renderer2), the component's ngOnDestroy method is not called.
You can see example here, https://stackblitz.com/edit/angular4-hs37d2
(The code that's doing inserting and removing components is located in el-render.directive.ts)
public ngAfterContentInit() {
console.log('[ElRenderDirective] ngAfterContentInit');
this.renderer.appendChild(this.element.nativeElement, this.elRender.nativeElement);
}
public ngOnDestroy() {
console.log('[ElRenderDirective] ngOnDestroy');
this.renderer.removeChild(this.element.nativeElement, this.elRender.nativeElement);
}
Notice that for example the code
console.log('[FirstElComponent] ngOnDestroy')
is never executed. Which is a problem, as there are some components which needs to be notified about no longer being in DOM.
How can I manually insert component into DOM, so removing it will call ngOnDestroy?