Confirm message before closing material dialog accidentally in Angular?

Ashish Kumar picture Ashish Kumar · Nov 27, 2018 · Viewed 9.4k times · Source

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

    })

Answer

Abhishek Kumar picture Abhishek Kumar · Nov 27, 2018

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