2

How to prevent MatDialog from closing when clicked outside but in all the dialogs in my Angular application ? I also realized that the escape key is not closing the dialog after setting disableClose to true so i added a hostlistener to force the close but it's not really the best solution... For a specific component I can do this.

export class MyAppComponent {  
  constructor(private dialog: MatDialog){}  
  open() {  
    this.dialog.open(ConfirmComponent, { disableClose: true });  
  }  
 
  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close();
  }

}

but how to do it globally for all the dialogs in my application instead of doing it in each dialog component and also apply the hostlistener?

Kivo
  • 385
  • 8
  • 24

1 Answers1

2

You can define global setting in provider

import { MAT_DIALOG_DEFAULT_OPTIONS } from '@angular/material/dialog';



@NgModule({
  providers: [
    { provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: { disableClose: true }}
  ]
})
Gajendra
  • 23
  • 2
  • Thanks for the answer but now the dialog is not closed after I hit the escape key ! And same concern, i don't want to add a hostlistener on each dialog ! See my updated question – Kivo Jul 09 '21 at 16:37
  • Seems like it's not possible, but If you are ok without backdrop then you can use { hasBackdrop: false } instead of { disableClose: true } and then you can achieve what you want. – Gajendra Jul 11 '21 at 14:25