Video Course

Routing Angular v2+ Applications: Lesson 21 of 23

CanActivate and CanActivateChild

Up Next

CanDeactivate

Autoplaying in 7 seconds!

Cancel

A CanActivate guard is useful when we want to check on something before a component gets used.

This is extremely useful for scenarios like:

  • checking if a user is authenticated
  • checking if a user has permission

app/shared/guards/auth-guard.service.ts

import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

  canActivate() {
    console.log('i am checking to see if you are logged in');
    return true;
  }

  canActivateChild() {
    console.log('checking child route access');
    return true;
  }

}

app/dashboard/dashboard.routing.ts

After creating the AuthGuard and adding it to our AppModule, we are able to use it in our routes:

export const dashboardRoutes: Routes = [
  {
    path: 'dashboard',
    children: [
      {
        path: '',
        canActivate: [AuthGuard],
        component: DashboardComponent
      },
      {
        path: 'users',
        component: DashboardUsersComponent,
        canActivateChild: [AuthGuard],
        children: [
          {
            path: '',
            component: DashboardUsersHomeComponent
          },
          {
            path: ':username',
            component: DashboardUserDetailsComponent,
            canDeactivate: [CanDeactivateGuard]
          }
        ]
      }
    ]
  }
];

Chris Sevilleja

156 posts

Co-founder of Scotch.io. Slapping the keyboard until something good happens.