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 { } }