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. export interface SampleComponentCanDeactivate {
  5. SamplecanDeactivate: () => boolean | Observable<boolean>;
  6. }
  7. @Injectable()
  8. export class SampleChangesGuard implements CanDeactivate<SampleComponentCanDeactivate> {
  9. constructor() {
  10. }
  11. canDeactivate(
  12. component: SampleComponentCanDeactivate
  13. ): boolean | Observable<boolean> {
  14. return component.SamplecanDeactivate()
  15. ? true
  16. : confirm(
  17. "WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes."
  18. );
  19. }
  20. }
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.