Angular 9 Material Dialog returning undefined on close

Viewed 2775

I'm using Angular 9 and have a Material dialog that is set to return "test" on close like this:

<mat-dialog-actions align='center'>
    <button mat-raised-button color='primary' [mat-dialog-close]='"test"'>
        Submit
    </button>
</mat-dialog-actions>

In my main page component, I'm subscribing to afterAllClosed:

  constructor(private matDialog: MatDialog) { }

  OpenMatDialog(data): void {
    this.matDialog.open(
      DialogComponent,
      { data },
    );

    if( !this.matDialogCloseSub$ )
      this.matDialogCloseSub$ = this.matDialog.afterAllClosed.subscribe(result => {
        console.log(result);
      });
  }

However, result always comes back as undefined. What am I doing wrong?

I have set the dialog component in app.module.ts in entrycomponents as follows:

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

The Observable afterAllClosed does not return any value, because it doesn't know which dialog data it should return. You should use, afterClosed from the MatDialogRef, which is returned from the open call:

OpenMatDialog(data): void {
  const dialogRef = this.matDialog.open(
    DialogComponent,
    { data },
  );

  if( !this.matDialogCloseSub$) {
    this.matDialogCloseSub$ = dialogRef.afterClosed.subscribe(result => {
      console.log(result);
    });
  }
}

However, considering you are using some custom global method OpenMatDialog, I do see some issues, but at least you know now how to get the result from a dialog :). You will have to use the dialog reference, not the dialog service.

Related