When exactly is component destroyed?
Asked Answered
S

1

38

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?

Surprise answered 6/4, 2017 at 15:36 Comment(0)
P
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.

Pantoja answered 6/4, 2017 at 16:58 Comment(5)
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()?Surprise
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.Marv
@GünterZöchbauer Is ngOndestroy is guaranteed to be called ?Enceladus
@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 #37643089 how to do some custom cleanup when a tab is closed.Marv
@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?Madonia

© 2022 - 2024 — McMap. All rights reserved.