36

In Angular 2 with Ahead-of-Time (AOT) compiling, I have a parent component and a child component, like this:

<div>
    <h1>I am a parent</h1>
    <myChild *ngIf="showChild"></myChild>
</div>

I know that the child template is inserted to the DOM dynamically.

If showChild is evaluated to false, when exactly does Angular destroy the child component? Or will Angular destroy the child component at all? Is that the time Angular invokes the onDestroy() method?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
gye
  • 1,374
  • 3
  • 16
  • 27

1 Answers1

31

When Angular runs change detection and the binding to the ngIf input of the NgIf directive is updated, NgIf removes the component from the DOM. After the component is removed from the DOM ngDestroy() is called and then the component is free to get garbage collected.

If the parent component is removed while the *ngIf expression is true, the parent and child will be destroyed together. I don't know what ngDestroy() is called first though.

William Denman
  • 3,046
  • 32
  • 34
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • If the child component is destroyed, how does angular deal with the memory footprint? How clean would the garbage collection will be, assuming I have unsubscribed and detached events in onDestroy()? – gye Apr 07 '17 at 17:20
  • Angular isn't involved with garbage collection. If there are no references to your component, then the JS VM will collect all related classes. Angular ensures that it doesn't hold any reference itself to a component after it was destroyed. – Günter Zöchbauer Apr 07 '17 at 17:33
  • @GünterZöchbauer Is ngOndestroy is guaranteed to be called ? – Royi Namir Jun 13 '18 at 09:32
  • @RoyiNamir when Angular removes the component or service, then yes, if you just close the tab, then Angular won't do any cleanup and it won't be called. See also https://stackoverflow.com/questions/37642589/how-can-we-detect-when-user-closes-browser/37642657#37642657 how to do some custom cleanup when a tab is closed. – Günter Zöchbauer Jun 13 '18 at 09:38
  • @GünterZöchbauer when is exactly ngOnDestroy is called ? my use case i subscribed to a strem and unsubscribed on ngOnDestroy but it didnot stop even i navigated to another route, then navigating to another route is not doesnot calls ngOnDestroy method, then how to stop that subscription right after navigating to another page? – Mohammed Apr 28 '22 at 10:32