Routing Angular Applications


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:

canDeactivate() {
    console.log('i am navigating away');

    // if the editName !==
    if ( !== this.editName) {
      return window.confirm('Discard changes?');

    return true;