How to Close a Mat Dialog Programmatically in Angular?

There are two ways to close a mat dialog programmatically in Angular.

First: Close the mat dialog from its component.ts file –

If you want to close the mat dialog from its component.ts file programmatically, you have to inject the MatDialogRef<DialogComponentName> in your dialog’s constructor.

The MatDialogRef has a built-in method close() which closes the mat dialog when it gets called.

Here is the code for it:

import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-my-dialog',
  templateUrl: './my-dialog.component.html',
  styleUrls: ['./my-dialog.component.css']
})
export class MyDialogComponent implements OnInit {

  constructor(private dialogRef: MatDialogRef<MyDialogComponent>) { }

  ngOnInit(): void {
  }

  closeDialog(){
    // Write your stuff here

    this.dialogRef.close(); // <- Close the mat dialog

  }
}

Second: Close the mat dialog from its parent

If you want to close the mat dialog from its parent component i.e. the component which has called the mat dialog, you can make use of the dialogRef to close it programmatically.

See the below implementation:

import { MatDialog } from '@angular/material/dialog';

openDialog(){
  // Open the dialog
  this.dialogRef = this.dialog.open(MyDialogComponent,{
    width:'60%',   
    height:'50%',  
  });

}

closeDialog(){
  this.dialogRef.close(); // <- Close the mat dialog
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.