首页 > 解决方案 > 在 Electron 中关闭 MatDialogRef

问题描述

我正在开发一个通过 Electron 2.0.5 编译的 Angular 5 应用程序。我 MatDialogRef用来获取用户输入(YesNo)并使用响应来管理一些业务逻辑。显示后MatDialogRef,我无法关闭它。

对话框的 HTML 参考: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>

逻辑: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();
  }

}

最后在我的 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
            }
        });
...

通过 VSCode 调试应用程序时,我可以确认 close() 方法正在被击中。对话框没有关闭,也没有控制台错误。如何关闭垫子对话框参考?

标签: angularelectron

解决方案


看来,您的代码缺少订阅:

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

替换switchMap_subscribe

请参阅此处的文档示例:https ://material.angular.io/components/dialog/overview#dialog-content


顺便说一句,您可以使用此替代方案,而无需mat-dialog-close指令:

请参阅https://blog.angular-university.io/angular-material-dialog/(第 5 步)

您可以通过以下方式将修改后的表单数据传回 AppComponent:

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

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

您现在可以通过以下方式接收对话数据:

dialogRef.afterClosed().subscribe(
    data => console.log("Dialog output:", data)
); 

推荐阅读