How to use CanDeactivate guard in Angular

CanDeactivate guards prevent users from accidentally leaving routes with unsaved changes by prompting for confirmation before navigation. As the creator of CoreUI with extensive Angular development experience since 2014, I’ve implemented CanDeactivate guards in numerous form-heavy applications to prevent data loss. The most effective approach creates a generic guard that components can implement to control when they can be deactivated. This pattern provides excellent user experience by protecting against accidental data loss while maintaining flexible navigation control.

Create a CanDeactivate guard with a component interface to control navigation away from routes with unsaved changes.

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

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

@Injectable({
  providedIn: 'root'
})
export class UnsavedChangesGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> | boolean {
    return component.canDeactivate ? component.canDeactivate() : true
  }
}

// In component
export class EditFormComponent implements CanComponentDeactivate {
  hasUnsavedChanges = false

  canDeactivate(): boolean {
    if (this.hasUnsavedChanges) {
      return confirm('You have unsaved changes. Do you really want to leave?')
    }
    return true
  }
}

// In routing
{
  path: 'edit/:id',
  component: EditFormComponent,
  canDeactivate: [UnsavedChangesGuard]
}

This code creates a reusable CanDeactivate guard that delegates the deactivation decision to components implementing the CanComponentDeactivate interface. Components can implement custom logic to determine if navigation should be allowed, such as checking for unsaved form data. The guard prompts users for confirmation when there are unsaved changes, preventing accidental data loss.

Best Practice Note:

This is the data protection pattern we implement in CoreUI form components to enhance user experience and prevent data loss. Consider using more sophisticated confirmation dialogs or auto-save functionality for better user experience in production applications.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team