2

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?

Martin Velinsky
  • 175
  • 1
  • 7
  • The components first, second and third are not destroyed as they added to the DOM. With the button you change just their hide and show status. When you update code, stackblitz would recreate the whole DOM, so you can see 'first destroyed' – Vega Mar 20 '18 at 21:16
  • I can see it beeing actually removed from DOM, it's not only show/hide – Martin Velinsky Mar 21 '18 at 09:42
  • 2
    I suggest using a different approach where you use `ComponentRef` so you can call `destroy()` method for the component reference, instead of just removing the DOM https://stackoverflow.com/a/36325468/1776220 – Daniel Cardenas Mar 21 '18 at 16:13
  • I think different approach of the design should help @DanielCardenas good suggestion. Anyway upvoted. –  Mar 21 '18 at 16:30
  • @Vega points to interesting idea though. The component is not destroyed, mere removing it from DOM does not mean component being destroyed. If it was, I would not be able to attach it back. If I want to listen to ngOnDestroy, I need to have a way to create the component from scratch, so I take control over its destruction – Martin Velinsky Mar 21 '18 at 17:14
  • 1
    Here is stackblitz example I made once, check it out please : https://stackblitz.com/edit/angular-q3cz5e – Vega Mar 21 '18 at 17:32

0 Answers0