Martin Vondracek
Martin Vondracek

Reputation: 101

Angular 2 - ngOnDestroy is not triggered

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

When I hide the first section with nested components using *ngIf, ngOnDestroy of every nested component is triggered.

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

Output in console is:

    init
    init
    init
    init
    init
    destroy
    destroy
    destroy
    destroy
    destroy

But when I hide the second section where subcomponents are duplicated by *ngFor, not every ngOnDestroy is triggered.

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

Output in console is:

(6) init
(3) destroy

Do you have any idea if I do something wrong, or there is an issue in angular2? Thanks.

Upvotes: 10

Views: 3786

Answers (2)

7vujy0f0hy
7vujy0f0hy

Reputation: 9109

In OP’s own words:

in angular beta 9 it works as I expected so they have a bug

Confirmed by OP’s own bug report (closed).

😀

Upvotes: 0

Dinesh Kumar
Dinesh Kumar

Reputation: 503

Try below mentioned code. it should work,

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

Upvotes: 1

Related Questions