angularangular-material2mddialog

Close md-dialog inside it's component.ts


I have a md-dialog component - DialogComponent - which i open from sibling component - SiblingComponent - and i want to close it in dialog.component.ts after some actions.

DialogComponent basically is a form with submit button, submitting form takes me to dialog.component.ts function where i'm doing some validation and sending data to service.

After validation passes and data is sent i want to make some timeout and then automatically close dial window, but i dont know how to run something like md-dialog-close in dialog.component.ts


Solution

  • You can inject an MdDialogRef into the dialog component class, and use that to close it. Example:

    export class DialogComponent {
    
        constructor(private dialogRef: MdDialogRef<DialogComponent >) { }
       
        someAction() {
            // do your thing here
            this.dialogRef.close(); // <- this closes the dialog. 
            // You can also wrap it in setTimeout() if you want
        }
    }
    

    Edit 2025

    import { MatDialogRef } from '@angular/material/dialog';
    
    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>) {}
    
      someAction() {
        this.dialogRef.close();
      }
    }