4

如何通过单击外部关闭此stackblitz 示例 (最小,可重现示例。)中的对话框?

如果我删除属性hasBackdrop: false->工作 Stackblitz 示例,这工作正常

4

3 回答 3

8

创建在对话框外单击时关闭的Angular Material 对话框的标准方法(同时创建没有背景的外观)是使用内置库 CSS 类cdk-overlay-transparent-backdrop并使用MatDialogConfig属性应用它backdropClass

openDialog方法将是:

openDialog(): void {
  const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
    backdropClass: 'cdk-overlay-transparent-backdrop',
    hasBackdrop: true,
    width: '250px'
  });
}

参见Stackblitz 示例

于 2019-09-11T00:44:36.463 回答
4

简而言之,您需要进行自己的点击处理 - 聆听点击并确定它们是否在对话框之外。这使您不会像背景一样捕获点击事件。这是基于您的 StackBlitz 示例:

@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();
  }
}
于 2019-09-11T16:24:49.157 回答
2

如何实现这一点有很多方法。一种是听窗口点击。堆栈闪电战

export class DialogOverviewExampleDialog {

  private inited;

  constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) { }

  ngOnInit() {
      this.dialogRef.afterOpened().subscribe(() => {
        this.inited = true;
      })
  }

  @HostListener('window:click')
  onNoClick(): void {
    if (this.inited) {
        this.dialogRef.close();
    }
  }

}

但我建议您编辑背景的 css,因此它仍然不可见,但功能仍然存在。

.cdk-overlay-dark-backdrop {
    background: transparent;
}
于 2019-09-10T21:33:59.397 回答