Prevent closing of Angular Material Dialog when escape button is pressed but allow closing when backdrop is clicked

二次信任 提交于 2019-12-07 04:37:01

问题


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');
  });
}

回答1:


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



来源:https://stackoverflow.com/questions/51010064/prevent-closing-of-angular-material-dialog-when-escape-button-is-pressed-but-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!