我目前正在一个Angular 4项目的密码重置页面上工作。我们使用Angular Material来创建对话框,但是,当客户端单击对话框时,它会自动关闭。有没有办法避免对话框关闭,直到我们的代码端调用“关闭”函数?或者我应该如何创建一个不可关闭的模式?


有两种方法。

In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true: export class AppComponent { constructor(private dialog: MatDialog){} openDialog() { this.dialog.open(DialogComponent, { disableClose: true }); } } Alternatively, do it in the dialog component itself. export class DialogComponent { constructor(private dialogRef: MatDialogRef<DialogComponent>){ dialogRef.disableClose = true; } }

以下是你想要的:

这是Stackblitz的演示


其他用例

下面是一些其他的用例和如何实现它们的代码片段。

允许esc关闭对话框,但不允许单击背景关闭对话框

正如@MarcBrazeau在我的回答下面的评论中所说,你可以允许esc键关闭模态,但仍然不允许在模态之外单击。在你的对话框组件上使用下面的代码:

import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
  selector: 'app-third-dialog',
  templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
  constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
}
  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close();
  }

}

防止esc关闭对话框,但允许单击背景关闭

附注:这是一个源于这个答案的答案,演示是基于这个答案。

为了防止esc键关闭对话框,但允许单击背景关闭,我已经改编了Marc的答案,以及使用matdialgref# backdropClick来监听背景的点击事件。

最初,对话框将配置选项disableClose设置为true。这可以确保按esc键以及单击背景不会导致对话框关闭。

然后,订阅matdialgref# backdropClick方法(当背景被单击时发出并作为MouseEvent返回)。

不管怎样,技术上的讨论已经够多了。代码如下:

openDialog() {
  let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
  /*
     Subscribe to events emitted when the backdrop is clicked
     NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
     See https://stackoverflow.com/a/41086381 for more info
  */
  dialogRef.backdropClick().subscribe(() => {
    // Close the dialog
    dialogRef.close();
  })

  // ...
}

或者,这也可以在dialog组件中完成:

export class DialogComponent {
  constructor(private dialogRef: MatDialogRef<DialogComponent>) {
    dialogRef.disableClose = true;
    /*
      Subscribe to events emitted when the backdrop is clicked
      NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
      See https://stackoverflow.com/a/41086381 for more info
    */
    dialogRef.backdropClick().subscribe(() => {
      // Close the dialog
      dialogRef.close();
    })
  }
}

如何处理这两个性质呢?

disableClose: boolean -用户是否可以使用转义或单击背景来关闭模式。 hasbackground: boolean -对话框是否有背景。 https://material.angular.io/components/dialog/api


Add

[config]="{backdrop: 'static'}"

到模态代码。