In my app, I want a feature that gives a warning message when I try to; close the tab, exit the page or reload the page. The code I wrote for it is below. Right now, it gives a warning. Yet, it still exits the page before I can click “yes” or “no”. How can I fix this?
HTML:
<div (window:beforeunload)="onWindowClose($event)"></div>
TS:
@HostListener('window:beforeunload', ['$event'])
onWindowClose(event: any): void {
this.confirmDialogRef = this._dialog.open(FuseConfirmDialogComponent, {
disableClose: false,
});
this.confirmDialogRef.componentInstance.confirmMessage =
"You will be exiting the page, are you sure?";
this.confirmDialogRef.afterClosed().subscribe((result) => {});
event.preventDefault();
event.returnValue = false;
}
Why not use a Directive to achieve this
@Directive({selector: 'button[counting]'})
class CountClicks {
numberOfClicks = 0;
@HostListener('click', ['$event.target'])
onClick(btn) {
console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
}
}
@Component({
selector: 'app',
template: '<button counting>Increment</button>',
})
class App {}