在 Angular 中意外关闭 material 对话框之前确认消息?

Confirm message before closing material dialog accidentally in Angular?

如何使用 beforeClose() 方法在关闭 material 对话框之前显示确认消息?

this.dialogRef.beforeClose().subscribe(result => {
      var cn = confirm('You have begun editing fields for this user. 
                        Do you want to leave without finishing?')
      console.log(cn);

    })

you can prevent to close dialog from click outside or escusing disableClose: true

let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: '250px',
      data: { name: this.name, animal: this.animal },
      scrollStrategy: this.overlay.scrollStrategies.close(),
      disableClose: true //for diabled close dialog
    });

您可以通过以下代码使用 confirmation 对话框:

 onNoClick(): void {
      var cn = confirm('You have begun editing fields for this user. Do you want to leave without finishing?');
       console.log(cn);
       if(cn){

    this.dialogRef.close();
       }
  };
  onOKClick(): void {
      var cn = confirm('You have begun editing fields for this user. Do you want to leave without finishing?');
       console.log(cn);
       if(cn){

    this.dialogRef.close();
       }
  };

HTML代码:

<div mat-dialog-actions>
  <button mat-button (click)="onNoClick()">No Thanks</button>
  <button mat-button (click)="onOKClick()" cdkFocusInitial>Ok</button>
</div>

reference Link: link1,

如你所愿 window.confirm 就以下几点 :

  • 如果用户点击刷新按钮,或者
  • 在对话框外单击

根据评论中分享的
我实现了 Stackblitz Demo,它使用 @HostListener
escrefresh 的代码:

@HostListener('window:keyup.esc') onKeyUp() {
    let cn = confirm('Sure ?')
    if (cn) {
      this.dialogRef.close();
    }
  }

@HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) {
      console.log('event:', event);
      event.returnValue = false;
}

并且在 ConfirmationDialog 组件中,将 backDropClick() 处理为

ngOnInit() {
  this.dialogRef.disableClose = true;
  this.dialogRef.backdropClick().subscribe(_ => {
    let cn = confirm('Sure ?')
    if (cn) {
      this.dialogRef.close();
    }
  })
}

申请代码: https://stackblitz.com/edit/dialog-example-beforeclose?file=app%2Fapp.component.ts