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