Angular5 Router Guards CanActivateChild & CanDeactivate

In last Article i discussion on the canActivate Router Guard. In this article we learn how to use “CanActivateChild” & “CanDeactivate” Guards.
CanActivateChild
For “CanActivateChild” Guard we need to create service for it. Let’s create service called “AuthChildrenRoute”.
Create file in service authchildernroute.ts OR create service using Angular CLI.

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

@Injectable()
export class AuthChildrenRoute implements CanActivateChild {

  constructor() { 
  }

canActivateChild() {
   console.log('Called active children');
    return true;
  }

}

In above code we have implements “CanActivateChild” and we need method “canActivateChild” in that Class.
Need to import this service in the module.ts & added in the provider then we need to import that services in our router.module.ts file. Then we can add that guard in our Router like below.


import { AuthChildrenRoute } from './services/authchildernroute';
const routes:Routes=[
    {'path':'',redirectTo: "signup",pathMatch: 'full'},
    {'path':'signup',
      canActivate:[AuthLoginGuard],
      component: SignupComponent
  },
    {'path':'user',
    canActivate:[AuthLoginGuard],
    canActivateChild:[AuthChildrenRoute],
    children: [
        {path: '', redirectTo: 'myaccount'},
        {path: '/myaccount', component: TestComponent}
     ],
    component: TestComponent
  }
];

In above code you can see “canActivateChild” Guard calls when child component called.
In Guard function we can pass the parameters. You can pass 3 types of parameter
1) Component : we can pass Full component
2) ActivatedRouteSnapshot : If Router is activated then we can use params of the Router.
3) RouterStateSnapshot : If Router guard pass then we can get current URL using it.


CanDeactivate Guard
This Guard calls when your leaves route at that time If we want to show any message we can display from this Route.
This Guard need at-least one parameter.

import { Injectable } from '@angular/core';
import { TestComponent } from '../pages/test/test.component';
import {CanActivateChild,CanDeactivate, ActivatedRoute,ActivatedRouteSnapshot,RouterStateSnapshot} from "@angular/router";

@Injectable()
export class AuthChildrenRoute implements CanActivateChild,CanDeactivate {

  constructor() { 
  }

 canActivateChild() {
   console.log('Called active children');
    return true;
  }

  canDeactivate(component:TestComponent,
    activeroute: ActivatedRouteSnapshot,
    routestate: RouterStateSnapshot) : boolean {

        console.log(routestate.url);
        console.log(activeroute.params);
        return true;

  }

}

In above you can see when we implements we need to pass one component on the “canDeactivate”. This ways we use Guards in Router. Any Issue related with Router Guard please comment below.

Spread the love
  • 44
  •  
  •  
  •  
  •  
  •  
  •  
  •