I want to persist value in the angular form input fields when a user navigate to different component like privacy policy and coming back to form. When the user comes back from privacy policy to form, he should see previously entered data
When a user clicks on the save button let's call the below method where it removes the old key and saves new form(MessageForm) data in local storage.
onSave() {
//removes the data with key as user
localStorage.removeItem("teja");
//adds new data with key as user
localStorage.setItem("teja", JSON.stringify(this.MessageForm.value));
//reset form once form is edited dirty flag is set
//so we need to reset form else on close we get
//notification saying form is dirty even when user clicked on save
this.MessageForm.reset(JSON.parse(localStorage.getItem('teja')));
}
When we load the page again we can retrieve the data from this storage with key 'teja'
ngOnInit(): void {
//retrieves data if exists.
if (localStorage.getItem('teja')) {
this.MessageForm.setValue(JSON.parse(localStorage.getItem('teja')));
}
}
@HostListener('window:beforeunload', ['$event']) unloadNotification($event: any) {
if (this.MessageForm.dirty) {
//store data
localStorage.setItem("teja", JSON.stringify(this.MessageForm.value));
//show popup
$event.returnValue = true;
}
}
using hostistener you can handle events like window closed or page refreshed. Within it, we are checking if the form is dirty which is set only when the user modifies the form. One problem you will see is if the user clicks on save and tries closing the window you still get the popup saying the user has unsaved data. That's because once the form is edited, its dirty flag is set. You need to reset it. Add the below logic to Onsave at the end
//reset form once form is edited dirty flag is set
//so we need to reset form else on close we get
//notification saying form is dirty even when user clicked on save
this.MessageForm.reset(JSON.parse(localStorage.getItem('teja')));
import { AppComponent } from './../app/app.component';
import { Injectable } from '@angular/core';
import { CanActivate, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UnsavedataGuard implements CanDeactivate<unknown> {
canDeactivate(
component: AppComponent): boolean {
if (component.MessageForm.dirty) {
localStorage.setItem("teja", JSON.stringify(component.MessageForm.value));
return confirm('Are you sure you want to continue? Any unsaved changes will be lost');
}
return true;
}
}
Update your route to access the guard
const routes: Routes = [
{ path: '', component: AppComponent, canDeactivate: [UnsavedataGuard] },
{ path: '**', component: AppComponent, pathMatch: 'full' }
];
Please find minified tutorial: https://tejaxspace.com/storage-local-session/
Please find an angular demo App: https://github.com/tejaswipandava/AngularDataPersistence.git
You can use
localStorage
. It is really easy to use.
var data = "some data";
localStorage.setItem("data_item", data);
localStorage.getItem("data_item"); //returns "some data"
Or
Use SessionStorage
or cookies to store your data.
When you hit refresh copy your data in any of the above storage and on init copy it back into your variable. Check below example. Replace the sessionStorage to localStorage to store data in localStorage.
In AppComponent
ngOnInit() {
if (sessionStorage.getItem("user")) {
this.data.changeUser(sessionStorage.getItem("user"));
}
}
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
sessionStorage.setItem("user", this.getUser());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With