Routing Angular Applications: Lesson 22 of 23


Up Next


Autoplaying in 7 seconds!


Implementing CanDeactivate can be a bit trickier than CanActivate, CanActivateChild, or Resolve.

The trick to CanDeactivate is that we need to make it reusable for multiple components. To do this, we'll create a guard that checks a component to see if it has a canDeactivate() method.


import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';

export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;

export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {

  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;



Then we need to implement it in our component:

Table of Contents

    canDeactivate() {
        console.log('i am navigating away');
        // if the editName !==
        if ( !== this.editName) {
          return window.confirm('Discard changes?');
        return true;

    Chris Sevilleja

    176 posts

    Founder of Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.