本文介绍了如何在不单击外部背景的情况下关闭垫对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在此 stackblitz示例 中关闭对话框(最小的,可复制的示例.),方法是在外部单击?
How Can I close the dialog in this stackblitz example (Minimal, Reproducible Example.) by clicking outside ?
如果我删除属性 hasBackdrop:false
-> 工作中的Stackblitz示例
This works fine if I remove the property hasBackdrop: false
-> Working Stackblitz Example
推荐答案
简而言之,您需要执行自己的单击处理-监听单击并确定它们是否在对话框之外.这使您可以不像背景那样捕获click事件.这是一个StackBlitz示例根据您的:
In a nutshell, you need to do your own click handling - listen to clicks and determine whether or not they are outside the dialog. This allows you to not trap the click event the way that the backdrop does. Here's a StackBlitz example based on yours:
@Component({
selector: 'dialog-overview-example',
templateUrl: 'dialog-overview-example.html',
styleUrls: ['dialog-overview-example.css'],
})
export class DialogOverviewExample {
@HostListener('document:click', ['$event'])
clickout(event) {
if (this.clickoutHandler) {
this.clickoutHandler(event);
}
}
animal: string;
name: string;
clickoutHandler: Function;
dialogRef: MatDialogRef<DialogOverviewExampleDialog>;
constructor(public dialog: MatDialog) {}
openDialog(): void {
setTimeout(() => {
this.dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
width: '250px',
hasBackdrop: false
});
this.dialogRef.afterOpened().subscribe(() => {
this.clickoutHandler = this.closeDialogFromClickout;
});
this.dialogRef.afterClosed().subscribe(() => {
this.clickoutHandler = null;
});
});
}
closeDialogFromClickout(event: MouseEvent) {
const matDialogContainerEl = this.dialogRef.componentInstance.hostElement.nativeElement.parentElement;
const rect = matDialogContainerEl.getBoundingClientRect()
if(event.clientX <= rect.left || event.clientX >= rect.right ||
event.clientY <= rect.top || event.clientY >= rect.bottom) {
this.dialogRef.close();
}
}
}
@Component({
selector: 'dialog-overview-example-dialog',
templateUrl: 'dialog-overview-example-dialog.html',
})
export class DialogOverviewExampleDialog {
constructor(
public hostElement: ElementRef,
public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
@Inject(MAT_DIALOG_DATA) public data: DialogData) {
}
onNoClick(): void {
this.dialogRef.close();
}
}
这篇关于如何在不单击外部背景的情况下关闭垫对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!