0

When opening a dialog with the following code

this.dialog.open(MyComponent, {
      ...
      disableClose: false,
      ...
    });

a dialog will be opened as we expect and when pressing ESC, that dialog is then closed. This behaviour is fine until we instead want to prevent closing. E.g. there is a form in that dialog and when material closes that dialog when the user presses ESC, it should give us the opportunity to do anything. In my case, pop up a new dialog with a question: 'Do you wish to save your changes' and then a 'yes', 'no' and 'cancel' button.

  • The 'yes' will save and regular flow continues (i.e. dialog close after click)

  • The 'no' will simply let the regular flow continue (i.e. dialog close after click)

  • The 'cancel' should neither save nor close the dialog.

I have set up this functionality by doing custom logic through prohibiting the framework to close it on pressing ESC.

this.dialog.open(MyComponent, {
      ...
      disableClose: true,
      ...
    });

and then manually listening to the ESC button to close the most upper dialog (since dialogs can be above eachother). This functionality is a bit dirty but does the trick but it then breaks again when for example the dialog which is to be closed has a form with a select box. This <select> box, when opened, is also closed when ESC has been pressed (as it should). But I do not want that ESC press to also close my dialog.

This is why I try to completely abandon the custom logic and want to fallback on the default behaviour. I just need a little tweak on it. I need to either intercept the closing.

A good way would be a beforeClose event. There is one present but the event args are abscent

const ref = this.dialog.open(MyComponent, args);
ref.beforeClosed().subscribe(async (evt) => {
  // This wont work since evt is undefined
  evt.cancel = await this.mayClose();
});

Another way would be able to asynchronously tell Material if it may even close at all before closing even initiates. E.g. through this fake property

this.dialog.open(MyComponent, {
      ...
      disableClose: false,
      mayClose: this.mayClose()
      ...
    });


private async mayClose()  : Promise<boolean> {
   // Open up a new dialog with the yes/no/cancel button and return true when yes/no and false when cancel
}

I believe my question differs from other questions in the part that I do not want to disable closing. I want to conditionally cancel the close.

Wouter V
  • 1
  • 1
  • 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) – Abdul Aziz Barkat May 10 '23 at 05:04

0 Answers0