I created an application where the user inputs data. On that application, I want to implement router guards to deny the user to go back on-page so that they don't lose their data. If the user clicks on the back button on the browser, it reloads page instead of going back?
I am thinking to use canDeactivate to deny access to the previous page and Angular Location to determine what page users are on then reload that page. But I don't how to implement this.
1. Create Service for CanDeactivate Guard
First you have to create an interface that will declare
canDeactivate
method and using this interface you will create a service that will act ascanDeactivate
guard. This service will definecanDeactivate
method as following:deactivate.guard.ts:
The interface has declared
canDeactivate
method whose return type is boolean. In the service code, we calledcanDeactivate
method using component instance.2. Configure CanDeactivate Guard Service in Application Routing Module
app.module.ts:
3. Create canDeactivate() method within Your Component
formComponent.ts:
4. Add CanDeactivate Guard to Component Route in Routing Module
You need to add our CanDeactivate guard .i.e. DeactivateGuard to component route in routing module using canDeactivate attribute.
app-routing.module.ts:
You might as well consider storing your data in a service as it might be a better choice.