How to Avoid Page Changes When You Have Unsaved Changes in Angular


Introduction:

Navigating away from a webpage with unsaved changes can lead to data loss and frustration. In this guide, we’ll explore effective methods to prevent page changes when you have unsaved changes in an Angular application. Whether you’re a developer or a user, understanding these techniques will help you safeguard your work. 

Why Preventing Page changes with unsaved changes matter..?Understanding the importance of preventing accidential navigation can save your time and prevent the loss of valuable information. When working on forms, editing documents, or entering data in Angular application, ensuring your changes are saved before leaving the page is crucial.

So, to avoid page change when we have unsaved changes we can use canDeactivateFn() method of route guard. Navigating away from a webpage with unsaved changes can lead to data loss and frustration. In this guide, we'll explore effective methods to prevent page changes when you have unsaved changes in an Angular application. Whether you’re a developer or a user, understanding these techniques will help you safeguard your work. Introduction

Our intution is, we will maintain a variable of boolean type which tells us that, we can exit the page or not, and we will use that variable in canDeactivateFn() route guard.

The component in which you have to check for changes, create a variable called ‘canExit’(or the name that you want) and according to your logic change the value to true or false.


Yourcomponent.ts file
export class YourComponent implements OnInit {

public canExit: boolean = true; //variable to maintain

ngOnInit(): void {
this.canExit = true;
}

public editMode(){
this.canExit = false;
}

public submit(){
this.canExit = true;
}
}

*In app.module.ts file, in routes add canDeactivate guard
import { UnSavedChangesGuard } from './guards/un-saved-changes.guard';
import { RegisterComponent } from './public/components/register/register.component';

const routes: Routes = [
//other routes
{ path: 'register', component: RegisterComponent, canDeactivate: [UnSavedChangesGuard]}
]

*canDeactivateFn() route guard code
import { CanDeactivateFn } from '@angular/router';

export const UnSavedChangesGuard: CanDeactivateFn<any> = (component, currentRoute, currentState, nextState) => {
let canExitPage: boolean = false;

let canExitPage = component.canExit;

if (!canExitPage) {
alert("You have unsaved changes"); //you can use confirm() also in place of alert()
return false;
}

return true;
};

Comments

Popular posts from this blog

Custom Validator to match Password and Confirm Password in Angular

Enhancing Express.js Requests with TypeScript: Adding User Objects and More