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

时间:2018-11-27 10:26:46

标签: angular angular-material angular-material2 angular-material-6

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

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);

    })

2 个答案:

答案 0 :(得分:2)

您希望window.confirm用于以下方面:

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

根据评论中共享的referrence link
我已经实现了 Stackblitz Demo ,它使用了@HostListener
esc refresh 的代码:

@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

答案 1 :(得分:1)

  

您可以阻止使用dialog来关闭outside或单击esc来关闭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>
  

参考链接:link1link2