Angular 2 - ngOnDestroy未被触发

时间:2016-05-03 19:32:37

标签: javascript angular

demo http://plnkr.co/edit/7uoVecfa62i8No8GtQHI?p=preview

当我使用* ngIf隐藏包含嵌套组件的第一部分时,会触发每个嵌套组件的ngOnDestroy。

<div *ngIf="!ff2">
    <my-component
    ></my-component>
    <my-component
    ></my-component>
    <my-component
    ></my-component>
    <my-component
    ></my-component>
    <my-component
    ></my-component>
  </div>

控制台中的输出是:

    init
    init
    init
    init
    init
    destroy
    destroy
    destroy
    destroy
    destroy

但是当我隐藏第二部分,其中子组件被* ngFor复制时,并不是每个ngOnDestroy都被触发。

 <div *ngIf="!ff">
        <my-component
          *ngFor="#i of [1,2,3,4,5,6]"
        ></my-component>
      </div>

控制台中的输出是:

(6) init
(3) destroy

你知道我做错了什么,或者angular2有问题吗?感谢。

2 个答案:

答案 0 :(得分:1)

尝试下面提到的代码。它应该工作,

<button type="button" (click)="ff = !ff">toggle</button>
<template ngFor let-item [ngForOf]="[1,2,3,4,5,6]">
  <my-component *ngIf="!ff"></my-component>
</template>

答案 1 :(得分:0)

OP’s own words中:

  

在角度测试版9中它按预期工作,因此他们有一个错误

由OP自己bug report确认(已结束)。