DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How to Improve Copilot's Accuracy and Performance in Power BI
  • Building a Real-Time Change Data Capture Pipeline With Debezium, Kafka, and PostgreSQL
  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques

Trending

  • Introduction to Retrieval Augmented Generation (RAG)
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • How to Format Articles for DZone
  • Strategies for Securing E-Commerce Applications
  1. DZone
  2. Data Engineering
  3. Data
  4. Prevent Users From Losing Unsaved Data

Prevent Users From Losing Unsaved Data

By 
Nitin Arora user avatar
Nitin Arora
·
Jan. 31, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
14.9K Views

Join the DZone community and get the full member experience.

Join For Free

There are many instances where a user fills some input in a form, edits that input, and then might attempt to leave the page that they're on. However, often, we'll want to secure the form in such a way that if someone navigates away or closes the browser tab, they should be prompted to confirm that they really want to leave the form with unsaved data.

Whenever these kinds of instances occur, you will see an alert appear on the top of your browser like this:

Leaving page alert
Leaving page alert
 Here, we have two different ways of implementing these functionalities: 


  • When a user closes or refreshes the tab.
  • When navigation is changed (user clicks back or forward navigation page buttons).

So, let's go ahead with the first implementation:

When a User Closes or Refreshes the Tab

We need to register the window:beforeunload and show a message if the user has unsaved data. The beforeunload event is fired when the window, the document, and its resources are about to be unloaded. The document is still visible, and the event is still cancelable at this point.

This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page; otherwise, it cancels the navigation.

For example:
JavaScript
 




x


 
1
@HostListener('window:beforeunload', ['$event'])
2
public onPageUnload($event: BeforeUnloadEvent) {
3
  if (this.hasUnsavedData()) {
4
    $event.returnValue = true;
5
  }
6
}



2: When the User Navigates to Another Route (Navigation Changed Event):

For the implementation of navigation changed events, you need to initially create a canDeactivate interface. It is an interface that a class can implement to be a guard, deciding if a route can be deactivated. If all guards return true, navigation will continue. If any guard returns false, navigation will be canceled. If any guard returns a UrlTree, current navigation will be canceled and new navigation will be kicked off to the UrlTree returned from the guard.


Initially, we need to write the import statement for canDeactivate , which comes from  '@angular/router'.

 
JavaScript
 




xxxxxxxxxx
1


 
1
import { CanDeactivate } from '@angular/router';
2
 
           



Then, we create an interface for the HasUnsavedDatamethod and import it as well in a guard file/component.
JavaScript
 




xxxxxxxxxx
1


 
1
export interface HasUnsavedData {
2
  hasUnsavedData(): boolean;
3
}




Add the path to the route config file.
JavaScript
 




xxxxxxxxxx
1


 
1
{path:'user/new',component:UserFormComponent,canDeactivate: [CanDeactivateGuard]}
2
 
           




Add CanDeactivate to the ngModuleproviders. Now, we write the main method to handle this event and showing the popups for displaying the message for unsaved data in the guard file.
JavaScript
 




xxxxxxxxxx
1
15


 
1
import { Injectable } from '@angular/core';
2
import { CanDeactivate } from '@angular/router';
3
 
           
4
import { HasUnsavedData } from './core.interface';
5
 
           
6
@Injectable()
7
export class HasUnsavedDataGuard implements CanDeactivate {
8
  canDeactivate(component: HasUnsavedData): boolean {
9
    if (component.hasUnsavedData && component.hasUnsavedData()) {
10
      return confirm('You have some unsaved form data.
11
 Are you sure, you want to leave this page?');
12
    }
13
    return true;
14
  }
15
}



We will have to implement the method, CanDeactivate, which gets the component instance and returns true or false. In this example, true will be returned if the message popped up and the user confirmed. Otherwise, the route won't be changed.

Conclusion

To sum up all the blog, as a best practice we should create a generic component to handle any form components. This abstract component will be registered to the browser event and the angular guard will invoke its API: CanDeactivate. It will alert the user that data is unsaved when the form is actually left, not submitted, and dirty.


Further Reading

  • Angular: Everything You Need to Know [Tutorials].
  • Angular Essentials.
Data (computing) Guard (information security)

Opinions expressed by DZone contributors are their own.

Related

  • How to Improve Copilot's Accuracy and Performance in Power BI
  • Building a Real-Time Change Data Capture Pipeline With Debezium, Kafka, and PostgreSQL
  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!