Search code examples
angularangular-materialangular-material-5

How to close all dialogs modal opened using angular-material at once


I'm using angular material dialogcomponent in my angular app to open a dialog box whenever an error comes from the server.

If multiple error comes at time it opens multiple dialog boxes that's fine for me.I want close all dialog boxes at once using closeAll method.

When try to use closeAll method getting this error:

error TS2339: Property 'closeAll' does not exist on type 'MatDialogRef<DialogComponent, any>'.

How I'm opening the dialog:

 constructor(private dialog: MatDialog) {}
const dialogRef = this.dialog.open(DialogComponent, {
          width: "500px",
          height: "500px",
          disableClose: true,
          hasBackdrop: true,
          data: { name: this.name, animal: this.animal }
        });

DialogComponent.ts

onClose(): void {
    this.dialogRef.closeAll();
  }
app.module.ts

@NgModule({
  declarations: [
    DialogComponent,
    ...
  ],
  imports: [
    MatDialogModule,
    BrowserAnimationsModule,
    ...
  ],
  providers: [
      ...
  ],
  entryComponents: [ DialogComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Can anyone please help me?


Solution

  • Inject MatDialog to the DialogComponent.ts

    import { MAT_DIALOG_DATA, MatDialogRef, MatDialog } from '@angular/material';
    
    export class DialogComponent  {
      constructor(private _dialog: MatDialog) { }
    
      public onClose(): void {
        this._dialog.closeAll();
      }
    }