3

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

Yatendra Dubey
  • 109
  • 1
  • 2
  • 8

3 Answers3

3
  • How to persist data after clicking of save button.

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')));
        }
      }

  • user modified the form without saving and tries closing the window, you have 2 choices either give a pop-up saying he has unsaved data or store the form in local storage. I am gonna mix both of them here.

      @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')));

  • Coming to the question of how to save data when the user navigates away to a different page without saving the data. Two choices
  1. When the user navigates to a different page give a popup or save data to localstorage create a guard like below (command: ng g guard guardname)

    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' }
    ];

  1. Save data to local storage the moment the user modifies the form -- I will leave the research of this part as code is not handy with me

Please find minified tutorial: https://tejaxspace.com/storage-local-session/

Please find an angular demo App: https://github.com/tejaswipandava/AngularDataPersistence.git

Tejaswi Pandava
  • 486
  • 5
  • 17
1

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());
    }
Chanaka Weerasinghe
  • 5,404
  • 2
  • 26
  • 39
0

Best solution - using states.

Simpliest solution - save values on input event. For example:

<input FormControl="name" (input)="saveValue"/>

In your ts:

saveValue() {
this.name = this.form.get('name').value;
}

And when you go back to your form, call reBuild function.

reBuild() {
this.form.get('name').setValue(this.name) ;
}
Tonya
  • 258
  • 1
  • 4
  • 12