什么时候Angular决定销毁一个组件

时间:2017-04-06 15:36:11

标签: angular components parent-child ondestroy

在Angular 2 with Ahead-of-Time(AOT)编译中,我有一个父组件和一个子组件,如下所示:

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

我知道子模板是动态插入DOM的。我的问题是当“showChild”被评估为false时,Angular究竟是否会破坏子组件?或者Angular会破坏儿童组件吗?这是Angular调用“onDestroy()”方法的时间吗?

以下是我之前向朋友发表的声明(如果我错了请纠正我):

  

当Angular看到DOM中不再需要某个组件时,它会   破坏组件。

1 个答案:

答案 0 :(得分:12)

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 ngDestory() is called first though.