Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
Martin Vondracek Avatar asked May 03 '16 19:05

Martin Vondracek


1 Answers

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>
like image 189
Dinesh Kumar Avatar answered Oct 01 '22 00:10

Dinesh Kumar