默认情况下,按下 esc 按钮时,对话框将关闭。但是,我不想要这种预期的行为。
我想要发生的是防止按下 esc 按钮时关闭,但仍然允许单击背景来关闭对话框。这怎么办?
我尝试过这样的事情。然而,它不起作用:
openEditDialog() {
const dialogRef = this.dialog.open(EditPlaceDialogComponent, {
width: '90%',
height: '720px'
});
dialogRef.keydownEvents().subscribe(e => {
if (e.keyCode === 27) {
e.preventDefault();
dialogRef.disableClose = false;
}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
您可以使用
disableClose
的 MatDialogConfig
选项。作为MatDialog#open
的第二个参数传入:
openDialog() {
this.dialog.open(MyDialogComponent, { disableClose: true });
// ...
}
这应该可以防止 esc 关闭对话框。
编辑:我通过调整Marc的答案(作为对我的答案的评论)以及使用
MatDialogRef#backdropClick
监听背景的点击事件来解决你所要求的问题。
最初,对话会将
disableClose
设置为 true
。这可确保按 esc
按键以及单击背景不会导致对话框关闭。
然后,订阅
MatDialogRef#backdropClick
方法(该方法在单击背景时发出并作为 MouseEvent
返回)。
无论如何,技术讨论已经足够了。这是代码:
openDialog() {
let dialogRef = this.dialog.open(EditPlaceDialogComponent, { disableClose: true /* Your other config options here */ });
/*
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();
})
// ...
}
以下解决方案对我有用:
https://material.angular.io/components/dialog/api#MatDialogConfig
const dialogProperty= {
disableClose: true,
width: '600px',
backdropClass: 'transparent',
data: {data: userDetails}
}
this.submitModelRef = this._matDialog.open(SaveDetailsDialogComponent, dialogProperty);