1

I am working on an Angular 5 app compiled through Electron 2.0.5. I am using MatDialogRef to get user input (Yes or No) and using the response to govern some business logic. After displaying the MatDialogRef, I cannot get it to close.

The HTML of the dialog ref: confirm.component.html

<div class="confirm">
  <h1 mat-dialog-title>Confirm</h1>

  <div mat-dialog-content>
    {{dialogData.message}}
  </div>

  <div mat-dialog-actions>
    <button mat-button [mat-dialog-close]="'cancel'" (click)="close()">No</button>
    <button mat-button [mat-dialog-close]="'yes'" cdkFocusInitial (click)="close()">Yes</button>
  </div>

</div>

The logic: confirm.component.ts

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

@Component({
  selector: 'app-confirm',
  templateUrl: './confirm.component.html',
  styleUrls: ['./confirm.component.scss']
})
export class ConfirmComponent implements OnInit {

  dialogData: any;

  constructor(private dialogRef: MatDialogRef<ConfirmComponent>,
    @Inject(MAT_DIALOG_DATA) private data: any) {
      this.dialogData = data;
    }

  ngOnInit() {
  }

  close() {
    this.dialogRef.close();
  }

}

And finally on my app.ts:

...
    const dialogRef = this.matDialog.open(ConfirmComponent, {
        data: {
            message: 'Yes or No?'
        }
    });

    return dialogRef.afterClosed()
        .switchMap(result => {
            if (result !== 'cancel') {
                // Do something
            } else {
                // Do something
            }
        });
...

When debugging the app through VSCode I can confirm the close() method is being hit. The dialog does not close and there are no console errors. How do I close the mat dialog ref?

Luke
  • 776
  • 9
  • 24

1 Answers1

4

It seems, your code is missing the subscription:

dialogRef.afterClosed().subscribe(result => {
  console.log(`Dialog result: ${result}`);
});

Replace the switchMap by subscribe

See docs example here: https://material.angular.io/components/dialog/overview#dialog-content


By the way, you can use this alternative, without the mat-dialog-close directive:

See https://blog.angular-university.io/angular-material-dialog/ (Step 5)

You can pass the modified form data back to AppComponent in the following way:

  <div mat-dialog-actions>
    <button mat-button (click)="close(false)">No</button>
    <button mat-button (click)="close(true)">Yes</button>
  </div>

and

  close(clickResult: boolean): void {
    this.matDialogRef.close(clickResult);
  }

You can now receive the dialog data in the following way:

dialogRef.afterClosed().subscribe(
    data => console.log("Dialog output:", data)
); 
jasie
  • 2,192
  • 10
  • 39
  • 54