Creating An Unsaved Changes Alert In Angular

Introduction

 
In a web application, if you fill some form and unknowingly click on other navigation, you might lose your data filled in the form. It might be difficult for a user to fill in the form once again. We can monitor the changes and we can give an alert to the user. In this article, I will show you how to implement unsaved changes alert to a user in Angular 7.
 
Step 1 - Create an Injectable class which implements CanDeactivate interface
 
Create an injectable export class (SampleChangesGuard) which implements the CanDeactivate interface and an export interface (SampleComponentCanDeactivate) like below.
  1. import { CanDeactivate } from "@angular/router";  
  2. import { Injectable } from "@angular/core";  
  3. import { Observable } from "rxjs/Observable";  
  4.   
  5. export interface SampleComponentCanDeactivate {  
  6.   SamplecanDeactivate: () => boolean | Observable<boolean>;  
  7. }  
  8.   
  9. @Injectable()  
  10. export class SampleChangesGuard implements CanDeactivate<SampleComponentCanDeactivate> {  
  11.   constructor() {  
  12.   
  13.   }  
  14.   
  15.   canDeactivate(  
  16.     component: SampleComponentCanDeactivate  
  17.   ): boolean | Observable<boolean> {  
  18.      
  19.       return component.SamplecanDeactivate()  
  20.         ? true  
  21.         : confirm(  
  22.             "WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes."  
  23.           );     
  24.   }  
  25. }  
Step 2 - Configure routes
 
We need to configure the routing. Import SampleChangesGuard in the app-routing.module.ts file.
  1. import { SampleChangesGuard } from './guards/sellout-changes-guard';  
Inside Routes array, an optional parameter, canDeactivate, is there. We need to add SampleChangeGaurd to the canDeactivate array like below.
  1. {  
  2.        path: 'test',  
  3.        component: TestComponent,  
  4.        canActivate:[SampleChangesGuard]  
  5.      }  
Step 3 - Configure component form.
 
First, we need to import SampleComponentCanDeactivate like below in the component where we have a form.
  1. import { SampleComponentCanDeactivate } from './../../guards/sellout-changes-guard';   
We need to check the form and implement the SampleComponentCanDeactivate like below. We need to add the below sample of code in the declaration part. 
 
Whenever a user fills the sampleForm and tries to navigate, he/she will get an alert like this. 
  1. @HostListener("window:beforeunload")  
  2.  selloutcanDeactivate(): Observable<boolean> | boolean {  
  3.      return (  
  4.          !this.sampleForm.dirty  
  5.      );  
  6.  }  
  7.  sampleForm: FormGroup;  
Create Angular Unsaved Changes Alert
 

Summary

 
In this article, I discussed how to create an unsaved changes alert using inbuilt CanDeactivate interface in Angular 7. Hope this article is useful.


Similar Articles