Protecting User Interaction: Angular Leave Page Guard

May 15, 2024

In web applications, user experience is paramount. Imagine a scenario where a user spends considerable time filling out a form or making changes on a page, only to accidentally navigate away and lose all their progress. Such instances can frustrate users and lead to a negative perception of the application. To mitigate this risk and enhance user experience, Angular provides a powerful feature called the Leave Page Guard.

What is a Leave Page Guard?

A Leave Page Guard is a mechanism in Angular that prompts users with a confirmation dialog before they navigate away from a page. It acts as a safety net, preventing users from accidentally leaving a page and potentially losing unsaved changes.

Implementation Steps

Create a Guard Service

First, we need to create a guard service that implements the CanDeactivate interface provided by Angular. This interface allows us to define a method that Angular will call when the user attempts to leave a page.

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 LeavePageGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> | boolean {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

Implement CanDeactivate Interface in Components

Next, we need to implement the CanDeactivate interface in the components where we want to activate the leave page guard. This involves defining a method named canDeactivate that returns an observable, promise, or boolean.

import { Component } from '@angular/core';
import { CanComponentDeactivate } from './leave-page.guard';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-my-component',
  template: `
    <!-- Your component template -->
  `
})
export class MyComponent implements CanComponentDeactivate {
  canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
    if (confirm('Are you sure you want to leave this page?')) {
      return true; // Allow leaving the page
    } else {
      return false; // Prevent leaving the page
    }
  }
}


Register the Guard in Your Routing Module

Finally, we need to register the leave page guard in the routing module of our Angular application. This associates the guard with specific routes, ensuring that it is triggered when users attempt to navigate away from those routes.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MyComponent } from './my-component.component';
import { LeavePageGuard } from './leave-page.guard';

const routes: Routes = [
  {
    path: 'my-component',
    component: MyComponent,
    canDeactivate: [LeavePageGuard] // Register the guard for this route
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


Conclusion

In conclusion, the Leave Page Guard in Angular is a simple yet effective way to enhance user experience by preventing accidental navigation away from pages with unsaved changes. By implementing this guard, developers can provide users with a safety net, ensuring that their data is protected and their interactions with the application are seamless. Incorporating such features not only improves user satisfaction but also contributes to the overall success of the application.

Related:

← Back to home

Raunak