按下退出按钮时防止关闭 Angular Material 对话框,但在单击背景时允许关闭 [英] Prevent closing of Angular Material Dialog when escape button is pressed but allow closing when backdrop is clicked
问题描述
默认情况下,当按下 esc 按钮时,对话框关闭.但是,我不想要这种预期的行为.
By default, when the esc button is pressed, the dialog closes. However, I don't want this intended behaviour.
我希望在按下 esc 按钮时阻止关闭,但仍允许单击背景以关闭对话框.这怎么办?
What I would like to happen is to prevent closing when the esc button is pressed but still allow a click on the backdrop to close the dialog. How can this be done?
我试过这样的事情.但是,它不起作用:
I've tried something like this. However, it doesn't work:
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');
});
}
推荐答案
您可以使用 MatDialogConfig
的 disableClose
选项.作为MatDialog#open
的第二个参数传入:
You can use the disableClose
option of MatDialogConfig
. Pass it in as the second parameter of MatDialog#open
:
openDialog() {
this.dialog.open(MyDialogComponent, { disableClose: true });
// ...
}
这应该可以防止 esc 关闭对话框.
This should prevent esc from closing the dialog.
我设法通过调整 Marc 的答案(作为对我的答案的评论)以及使用 MatDialogRef#backdropClick
来解决您的要求单击背景中的事件.
I managed to solve what you asked for by adapting Marc's answer (as a comment on my answer), as well as using MatDialogRef#backdropClick
to listen for click events to the backdrop.
最初,对话会将 disableClose
设置为 true
.这可确保 esc
按键以及点击背景不会导致对话框关闭.
Initially, the dialogue will have disableClose
set as true
. This ensures that the esc
keypress, as well as clicking on the backdrop will not cause the dialogue to close.
之后,订阅 MatDialogRef#backdropClick
方法(当背景被点击时发出并作为 MouseEvent
返回).
Afterwards, subscribing to the MatDialogRef#backdropClick
method (which emits when the backdrop gets clicked and returns as a MouseEvent
).
无论如何,足够的技术谈话.代码如下:
Anyways, enough technical talk. Here's the code:
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();
})
// ...
}
Stackblitz 演示(点击打开第四个对话框"进行测试!)一个>
这篇关于按下退出按钮时防止关闭 Angular Material 对话框,但在单击背景时允许关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!