By default, when the esc button is pressed, the dialog closes. However, I don't want this intended behaviour.
What I would like to happen is to prevent closing when the esc button is pressed but still allow a click on the backdrop to close the dialog. How can this be done?
I've tried something like this. However, it doesn't work:
openEditDialog() {
const dialogRef = this.dialog.open(EditPlaceDialogComponent, {
width: '90%',
height: '720px'
});
dialogRef.keydownEvents().subscribe(e => {
if (e.keyCode === 27) {
e.preventDefault();
dialogRef.disableClose = false;
}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
You can use the disableClose
option of MatDialogConfig
. Pass it in as the second parameter of MatDialog#open
:
openDialog() {
this.dialog.open(MyDialogComponent, { disableClose: true });
// ...
}
This should prevent esc from closing the dialog.
EDIT: I managed to solve what you asked for by adapting Marc's answer (as a comment on my answer), as well as using MatDialogRef#backdropClick
to listen for click events to the backdrop.
Initially, the dialogue will have disableClose
set as true
. This ensures that the esc
keypress, as well as clicking on the backdrop will not cause the dialogue to close.
Afterwards, subscribing to the MatDialogRef#backdropClick
method (which emits when the backdrop gets clicked and returns as a MouseEvent
).
Anyways, enough technical talk. Here's the code:
openDialog() {
let dialogRef = this.dialog.open(EditPlaceDialogComponent, { disableClose: true /* Your other config options here */ });
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(_ => {
// Close the dialog
dialogRef.close();
})
// ...
}
Stackblitz demo (click on "Open fourth dialog" to test it out!)