Confirm message before closing material dialog accidentally in Angular?

17.1k Views Asked by At

How can i use of beforeClose() method to show a confirmation message before closing the material dialog ?

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

There are 2 best solutions below

3
On BEST ANSWER

As you want the window.confirm on the following things :

  • if user hit the refresh button, or
  • click outside of the dialog

According to referrence link shared in comments,
i have implemented a Stackblitz Demo, which uses @HostListener
Code for esc, and 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;
}

And in ConfirmationDialog component, handle backDropClick() as

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

Application Code : https://stackblitz.com/edit/dialog-example-beforeclose?file=app%2Fapp.component.ts

1
On

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

You can use confirmation dialog with below code :

 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 Code :

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

reference Link: link1, link2