Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 490
Brivvirs Avatar asked Sep 16 '17 13:09

Brivvirs


People also ask

How do you close a material dialogue?

To close a mat dialog from its component. ts file or programmatically, we have to inject the MatDialogRef<DialogComponentName> in its constructor. The MatDialogRef has a built-in method close() , which you can call anytime whenever you want to close the mat dialog box.

How do you prevent material dialog close on click outside?

By default, dialog can be closed by pressing Esc key and clicking the close icon on the right of dialog header. It can also be closed by clicking outside of the dialog using hide method. Set the closeOnEscape property value to false to prevent closing of the dialog when pressing Esc key.

What is MatDialog used for in angular material?

The MatDialog service can be used to open modal dialogs with Material Design styling and animations.

How do you increase the size of dialog box in angular materials?

The resizable dialog can be created by setting the enableResize property to true, which is used to change the size of a dialog dynamically and view its content with expanded mode.


1 Answers

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

like image 137
yurzui Avatar answered Oct 15 '22 21:10

yurzui