1

I have a component which contains a form.

If a user clicks refresh button in browser. Then it displays a modal popup warning the user that he might lose the form data and ask whether he would like to continue or not?

If the user chooses "No" then he does not lose the filled in form data.

The problem that Im facing is the modal dialog opens on refresh but it doesn't stop the page refresh.

Thanks in advance

Here is my code

//App Component

import { Component, HostListener } from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})

export class AppComponent {
title = 'test-hostlistener';

@HostListener('window:beforeunload') onRefresh() {
 this.dialog.open(DialogAnimationsExampleDialog);
}

constructor(private dialog: MatDialog) {}

//DialogAnimationsExampleDialog Component

@Component({
 selector: 'dialog-animations-example-dialog',
 template: `
  <h1 mat-dialog-title>Refresh page</h1>
  <div mat-dialog-content>
   If you refresh the page all data would be gone. Continue?
  </div>
  <div mat-dialog-actions>
   <button mat-button mat-dialog-close cdkFocusInitial color="accent">Yes</button>
   <button mat-button mat-dialog-close color="warn">No</button>      
  </div>
 `,
})
export class DialogAnimationsExampleDialog {
 constructor(public dialogRef: MatDialogRef<DialogAnimationsExampleDialog>) {}
}
coloraddict
  • 113
  • 1
  • 12
  • Does this answer your question? [How to pop up an alert box when the browser's refresh button is clicked?](https://stackoverflow.com/questions/3221161/how-to-pop-up-an-alert-box-when-the-browsers-refresh-button-is-clicked) – Chris Hamilton Jul 28 '22 at 21:46
  • See also: https://stackoverflow.com/q/38879742/12914833 – Chris Hamilton Jul 28 '22 at 21:51

0 Answers0