Search code examples
javascripttypescriptangular7

How to store reactive form data to localstorage?


I want to store reactive forms data to local storage and access that data to another page.

<form [formGroup]="testform" >
      firstname:
          <input type="text" formControlName="fname"><br>
      lastname:
          <input type="text" formControlName="lname">
          <button type="submit" (click)="Submit(testform)">Submit</button>
</form>

I hope anyone knows the issue. Thank you.


Solution

  • To set the value:

    JSON.stringify() is needed if you are storing an object.

    localStorage.setItem('form-data', JSON.stringify(this.testform.value));
    

    and to get the stored object from localStorage:

    let formValue = JSON.parse(localStorage.getItem('form-data'))