How to Prevent a Mat Dialog From Closing When Clicked Outside?

By default, you can close a mat dialog either by clicking outside of it or by pressing the escape key. This is the default behavior of a mat dialog.

However, in some situations, you might need to prevent this default behavior and you might want to close the mat dialog only when clicking on the close button.

There are two ways to prevent this behavior.

First: Using the parent component(the component where the mat dialog is called) –

To prevent a mat dialog from closing when clicked outside using the parent component, you have to pass a second parameter disableClose to the Matdialog.open() function and set it to true:

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

export class ParentComponent implements OnInit {

  constructor(private dialog: MatDialog) { }
  
  openDialog(){
    // Open the dialog
    const dialogRef = this.dialog.open(MyDialogComponent,{
      width:'60%',   
      height:'50%',  
      disableClose: true  // Prevent default closing
    });
  }
}

Second: Using the dialog’s component.ts file

In this method, you have to first inject the MatDialogRef<DialogComponentName> in the dialog’s constructor. The MatDialogRef object has a property disableClose. You have to simply set its value to true inside the constructor body to prevent the default behavior.

Here is the implementation:

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

export class MyDialogComponent implements OnInit {

  constructor(private dialogRef: MatDialogRef<MyDialogComponent>) {
    this.dialogRef.disableClose = true;
   }

  ngOnInit(): void {
  }

}

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.