Video Course

Routing Angular v2+ Applications: Lesson 22 of 23

CanDeactivate

Up Next

Wrapup

Autoplaying in 7 seconds!

Cancel

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.

app/shared/guards/can-deactivate-guard.service.ts

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

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

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {

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

}

app/dashboard/users/dashboard-user-details.component.ts

Then we need to implement it in our component:

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

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

    return true;
}

Chris Sevilleja

157 posts

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