In this tutorial, we will be discussing how to use the CanDeactivate guard in an Angular application. The CanDeactivate guard is used to prevent a user from navigating away from a route if there are unsaved changes in a form. This can be useful for situations where a user is filling out a form and accidentally navigates away from the page, potentially losing their progress.
We will be using a student profile form as an example to show how to implement the CanDeactivate guard in an Angular application.
How to use CanDeactivate in Angular App?
Follow these quick steps to create a sample application to demonstrate the use of CanDeactivate guard:
Step 1: Create a new Angular application
Step 2: Create a Student Profile Form Component
Step 3: Implement the Student Profile Form
Step 4: Create a CanDeactivate Service
Step 5: Implement the CanDeactivate Service
Step 6: Add the CanDeactivate Guard to the Router
Step 7: Test the App
Prerequisites
Before we begin, make sure you have the following installed:
- Node.js
- Angular CLI
Step 1: Create a new Angular application
To create a new Angular application, open the command prompt and run the following command:
ng new myApp
This will create a new Angular application with the name “myApp” in a new directory.
Step 2: Create a Student Profile Form Component
To create a Student Profile Form Component, open the command prompt and navigate to the root of your Angular application. Run the following command:
ng g component student-profile
This will create a new Student Profile Form Component in the “src/app” directory.
Step 3: Implement the Student Profile Form
Open the “src/app/student-profile/student-profile.component.html” file and add a form with input fields for the student’s name, age, and major.
<form>
<label>Name: <input [(ngModel)]="student.name" name="name"></label>
<br>
<label>Age: <input [(ngModel)]="student.age" name="age"></label>
<br>
<label>Major: <input [(ngModel)]="student.major" name="major"></label>
</form>
Step 4: Create a CanDeactivate Service
To create a CanDeactivate service, open the command prompt and navigate to the root of your Angular application. Run the following command:
ng g service can-deactivate
This will create a new CanDeactivate service in the “src/app” directory.
Step 5: Implement the CanDeactivate Service
Open the “src/app/can-deactivate.service.ts” file and import the Injectable decorator. Create a method that will check if the form has been modified and prompt the user to confirm if they want to navigate away from the page.
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { StudentProfileComponent } from './student-profile/student-profile.component';
@Injectable({
providedIn: 'root'
})
export class CanDeactivateService implements CanDeactivate<StudentProfileComponent> {
canDeactivate(component: StudentProfileComponent) {
if (component.form.dirty) {
return confirm('Are you sure you want to navigate away? Any unsaved changes will be lost.');
}
return true;
}
}
Step 6: Add the CanDeactivate Guard to the Router
Open the “src/app/app-routing.module.ts” file and import the CanDeactivate service and the Student Profile Form Component. Add the CanDeactivate guard to the route for the Student Profile Form Component.
import { CanDeactivateService } from './can-deactivate.service';
import { StudentProfileComponent } from './student-profile/student-profile.component';
const routes: Routes = [
{ path: 'student-profile', component: StudentProfileComponent, canDeactivate: [CanDeactivateService] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 7: Test the App
To test the app, run the following command:
ng serve
You should now be able to navigate to the “student-profile” route and fill out the form. If you try to navigate away from the page while the form has unsaved changes, you will be prompted to confirm if you want to navigate away.
Other Uses
The CanDeactivate guard can be used in other forms throughout the application, it can also be used in combination with other types of guards such as AuthGuard to create more advanced access control mechanisms in your application.
Conclusion
In this tutorial, we have discussed how to use the CanDeactivate guard in an Angular application. We have shown how to create a CanDeactivate service and add it to the router to prevent a user from navigating away from a route if there are unsaved changes in a form. This can be useful for situations where a user is filling out a form and accidentally navigates away from the page, potentially losing their progress.
Leave a Reply