禁用在角材质对话框区域外单击以关闭对话框(angular 4.0+版本)

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

187819 次浏览

有两种方法。

  1. 在打开对话框的方法中,传入以下配置选项disableClose作为MatDialog#open()中的第二个参数,并将其设置为true:

    export class AppComponent {
    constructor(private dialog: MatDialog){}
    openDialog() {
    this.dialog.open(DialogComponent, { disableClose: true });
    }
    }
    
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent {
    constructor(private dialogRef: MatDialogRef<DialogComponent>){
    dialogRef.disableClose = true;
    }
    }
    

Here's what you're looking for:

<code>disableClose</code> property in material.angular.io

And here's a Stackblitz demo


Other use cases

Here's some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

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的答案,以及使用MatDialogRef#backdropClick来监听背景的点击事件。

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

然后,订阅MatDialogRef#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 -用户是否可以使用转义或单击背景来关闭模式。

hasBackdrop: boolean -对话框是否有背景。

< a href = " https://material.angular。io /组件/对话框/ api noreferrer“rel = > https://material.angular.io/components/dialog/api < / >

添加

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

到模态代码。