Angular how to prevent user from reload or go back using route guard. I have basically a component and i want to make sure that when user click on reload the page or go back, it will then return to my home page. I did try canDeactivate but doesnt seems to do the tricks.
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable({
providedIn: 'root'
})
export class ConfirmLeaveGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> | boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
export class ReceiptComponent implements CanComponentDeactivate{
private router = inject(Router);
// Example method to prompt user before leaving
canDeactivate(): boolean {
// Example logic to prompt user with confirmation
return confirm('Are you sure you want to leave? Your data may be lost.');
}
{
path: 'receipt',
loadComponent: () => import('receipt.component').then(({ ReceiptComponent }) => ReceiptComponent),
canDeactivate: [ConfirmLeaveGuard]
},
Apart from canDeactivate
you also need to listen for the event window:beforeunload
and then trigger canDeactivate also in the component.
@HostListener('window:beforeunload')
canDeactivate(): any {
return component.canDeactivate();
}