18

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');
  });
}
Edric
  • 24,639
  • 13
  • 81
  • 91
  • Does this answer your question? [Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)](https://stackoverflow.com/questions/46772852/disable-click-outside-of-angular-material-dialog-area-to-close-the-dialog-with) – reverie_ss Apr 10 '20 at 15:09

2 Answers2

38

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!)

Edric
  • 24,639
  • 13
  • 81
  • 91
0

Below Solution works for me:

enter image description here

https://material.angular.io/components/dialog/api#MatDialogConfig

    const dialogProperty= {
      disableClose: true,
      width: '600px',
      backdropClass: 'transparent',
      data: {data: userDetails}
    }
    this.submitModelRef = this._matDialog.open(SaveDetailsDialogComponent, dialogProperty);
Abdullah
  • 2,393
  • 1
  • 16
  • 29