Adding the canActivate Route Guard to the Router Module
Learn how the canActivate Route Guard works in Angular.
What is the canActivate
route guard?
The canActivate
guard is a default route guard interface provided by Angular. It checks if a user can navigate a specific route or helps prevent access to a particular route. The canActivate
guard usually returns a boolean value and an
Integrating the canActivate
route guard
To integrate the canActivate
guard into our project, we need to take the following steps explained below:
Step 1: Creating the guard
To create the guard, we need to run the command below at the root of our Angular application:
ng generate guard auth/auth
Next, we get a prompt message in the terminal with the following options:
>(*) CanActivate
( ) CanActivateChild
( ) CanDeactivate
( ) CanLoad
By pressing the “Enter” key, we select the canActivate
option from the above prompt, and the guard gets created. Our folder structure should look like this:
src > app > components > auth
Inside the auth
folder, we have the following files generated by the Angular CLI:
auth.guard.spec.ts
auth.guard.ts
Get hands-on with 1400+ tech skills courses.