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 ofMatDialogConfig
. Pass it in as the second parameter ofMatDialog#open
: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 astrue
. This ensures that theesc
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 aMouseEvent
).Anyways, enough technical talk. Here's the code:
Stackblitz demo (click on "Open fourth dialog" to test it out!)