Search code examples
angularcomponentsparent-childondestroy

When exactly is component destroyed?


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?


Solution

  • 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.