Prevent user from navigating away from or closing the page

July 5, 2021 · 2 min readLucian Ciobanu
Tags:Angular

How to prevent the user from navigation or closing the tab on which he has unsaved changes in Angular?

  1. create a new guard

can-deactivate-guard.ts

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

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

@Injectable()
export class PendingChangeGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    return component.canDeactivate() ?
      true:
      confirm('There are unsaved changes. Are you sure you want to close?');
  }
}

  1. include guard in routing

app-routing.module.ts

import { PendingChangesGuard } from './shared/utilities/can-deactivate-guard';

const routes: Routes = [
  { path: 'componentWithPendingChanges', canDeactivate:[PendingChangesGuard], component: NameComponent }
];


  1. make the class injectable

app.module.ts

import { PendingChangesGuard } from './shared/utilities/can-deactivate-guard';

@NgModule({
  providers: [PendingChangesGuard],
})
  1. use it in your components
import { Component, HostListener } from '@angular/core';
import { ComponentCanDeactivate } from '../shared/utilities/can-deactivate-guard';

export class NameComponent implements ComponentCanDeactivate {
  //property unsaved changes should turn true once something has changed
  //and you do not wish to lose it
  @HostListener('windwo:beforeunload')
  canDeactivate(): boolean | observable<boolean> {
    return !this.unsavedChanges;
  }
  
  

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery