Brivvirs
Brivvirs

Reputation: 2493

Angular Material destroy dialog instance

Is there a proper way to destroy component instance which is created by dialog. When i close the dialog- component instance is not disposed:

import { Component, OnInit, Input, Output, EventEmitter, Inject } from '@angular/core';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';

@Component({
    selector: 'basket',
    templateUrl: './basket.component.html',
    styleUrls: ['./basket.component.css']
})
export class BasketComponent implements OnInit {
    @Input() Product: any;
}

@Component({
    selector: 'basket-dialog',
    template: '<div><basket [Product]="Product"></basket></div>'
})
export class BasketDialogComponent implements OnInit {
    Product: any;
    constructor(public dialogRef: MdDialogRef<BasketComponent>,
        @Inject(MD_DIALOG_DATA) public productData: any) { }


    ngOnInit() {
        this.Product = this.productData;
        this.say();
    }

    say() {
        setTimeout(() => this.say(), 1000);
        console.log('test');
    }
}

Create dialog:

let ordersDialog = this.dialog.open(BasketDialogComponent, {
    data: product
});
ordersDialog.afterClosed().subscribe(x => {
   // something like: orderDialog.componentInstance.dispose();
});

The say() method is still being executed even after dialog is closed.

Upvotes: 10

Views: 14531

Answers (2)

flyingpluto7
flyingpluto7

Reputation: 1099

I dispose my dialog after close like this. Just set your opened dialog reference to null.

let ordersDialog = this.dialog.open(BasketDialogComponent, {
    data: product
});
ordersDialog.afterClosed().subscribe(x => {
   ordersDialog = null;
});

Upvotes: 0

yurzui
yurzui

Reputation: 214085

You should care about disposing setTimeout yourself:

export class BasketDialogComponent implements OnInit, OnDestroy {

  timeoutId;

  say() {
    this.timeoutId = setTimeout(() => this.say(), 1000);
    console.log('test');
  }

  ngOnDestroy() {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
  }
}

Plunker Example

Upvotes: 3

Related Questions