• Angular
  • React
  • NextJs
  • Sass

How to Use canDeactivate in Angular

By Webrecto, September 10, 2023

The canDeactivate is a functional route guard. It prevents you from leaving the component when navigating to another component.

1: The canDeactivate decides if the current user is allowed to deactivate the component.

2: In the application, The canDeactivate guard is used to control the navigation change. If a user wants to change a component from click navigation, it prevents to change component.

3: The canDeactivate route guard accepts Array<CanDeactivateFn<any>> type data.

4: The CanDeactivate checks whether the user changes in the component have been saved before navigating away from the route.

Code Snippet:

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

@Injectable()
export class RouteGuardService {
  canDeactivate(component: CanComponentDeactivate, state: RouterStateSnapshot) {
      ---------
  }
} 

In the code snippet, I created one canDeactivate method in RouteGuardService class and imported RouteGuardService in the routing module.

We use canDeactivate method in the route path and pass two parameters one is component and the other is state.

If canDeactivate method of RouteGuardService returns true, then the current user deactivates the component and if returns false, the current user can not deactivate the component.

Complete Example:

In this example, I will create one demo application, and inside the application, I will create two feature modules one is employee, and the other is customer. In the employee section, I created employee details form for saving data and using canDeactivate route guard.

1: I created an employee routing module and configured all dependencies. I added the employee path and component in the route object and also added canDeactivate route guard.

2: Next step, I created the can-deactivate-guard.service and here I created one CanComponentDeactivate interface. The interface check return value is true or false.

3: When I fill in employee details in the form and during form filling try to switch to the next tab without saving data, canDeactivate route guard active and prevent switch navigation and show the message "Discard unsaved employee details?".

employee-routing.module.ts

import { NgModule, inject } from '@angular/core';
import { RouterModule, RouterStateSnapshot, Routes } from '@angular/router';
import { EmployeeComponent } from './employee.component';
import { AddEmployeeComponent } from './add-employee/add-employee.component';
import { CanComponentDeactivate, CanDeactivateGuard } from '../can-deactivate-guard.service';

const employeeRoutes: Routes = [
{
	path: 'employee',
	component: EmployeeComponent,
	children: [
          {
            path: 'add',
            component: AddEmployeeComponent,
            canDeactivate: [
            (component: CanComponentDeactivate, state: RouterStateSnapshot) =>
              inject(CanDeactivateGuard).canDeactivate(component, state)
            ]
          }
	 ]
   }
];

@NgModule({
	imports: [RouterModule.forChild(employeeRoutes)],
	exports: [RouterModule]
})
export class EmployeeRoutingModule { }

can-deactivate-guard.service.ts

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

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

@Injectable()
export class CanDeactivateGuard {
  canDeactivate(component: CanComponentDeactivate, state: RouterStateSnapshot) {
    let url: string = state.url;
    console.log('Url: ' + url);
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

dialog.service.ts

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable()
export class DialogService {
  confirm(message?: string): Observable {
    const confirmation = window.confirm(message || 'Are you sure?');

    return of(confirmation);
  };
}

Find the print screen of the output.

How to Use canDeactivate in Angular

Reference

Download Source Code