Retain Form data even when the user refreshes or reloads the page

My Form includes validation as shown below:

<form  [formGroup]="LoginForm">
  First name:<br>
  <input type="text" formControlName="firstname" >
  <br>
  Last name:<br>
  <input type="text" formControlName="lastname">
  <button  type="submit"  [disabled]="!this.LoginForm.valid"></button>
</form> 

component.ts

LoginForm: FormGroup;

onloginUser() {
    this.LoginForm = this.form.group({
      firstname: ['', Validators.required],
      lastname: ['', Validators.required],
    })
  }

I implemented a local storage service with the following code,

this.storage.set("user_data",this.LoginForm.value);
this.storage.get("user_data");

The issue I am facing is that when a user reloads the page or navigates back/forward, the data should remain in the input fields. However, the above code is not achieving this.

I have already checked the suggestions on stackoverflow at the following link: link, but none of the answers provided a solution for my specific case. Can anyone offer a better answer that would be helpful to me?

Answer №1

This is the TypeScript code I've prepared for this particular query

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-reload',
  templateUrl: './reload.component.html',
  styleUrls: ['./reload.component.css']
})

export class ReloadComponent  {    
    LoginForm: FormGroup;

    constructor(private FB: FormBuilder ) { 

    // 1 - Retrieving values from local storage
    const value = JSON.parse(localStorage.getItem('formValue')!);

    // 2 - Initializing form with saved values
    this.LoginForm = FB.group({
      firstname: [value && value.firstname || '', Validators.required],
      lastname: [value && value.lastname || '', Validators.required]
    });
  
    // 3 - Updating local storage on every change
    this.LoginForm.valueChanges.subscribe(value => {
      localStorage.setItem('formValue', JSON.stringify(this.LoginForm.value));
    });
  }
}
   

Answer №2

Make sure to assign a value to your form during initialization.

this.LoginForm.patchValue(this.storage.get("user_data"));

This code will function correctly if the storage service returns an object.

Answer №3

Whenever you navigate the component, it is recreated along with the form. Make sure to verify if there is any data in the local storage. If there is, assign it to the form after it has been created.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for deploying an Ionic 4 app on the Firebase console

I'm encountering issues deploying my Ionic app on the Firebase console. Here are the steps I've taken: Created a new Ionic project Ran firebase init and firebase deploy commands Unfortunately, I cannot seem to view the Ionic output after depl ...

Advantages of utilizing Observables instead of HTTP in Angular

As a newcomer to Angular, I am navigating the decision between utilizing rxjs/Observables versus simply using Http get/post calls. My research has indicated that Observables are most suitable for scenarios where data needs to be loaded asynchronously in a ...

Encountering an issue while setting up a new Angular application - receiving an error stating: "Module 'rxjs' cannot be found"

I encountered an issue while trying to create a new Angular app using the node command prompt. The error message displayed is as follows: internal/modules/cjs/loader.js:651 throw err; Error: Cannot find module 'rxjs' Node JS Version : v11.11. ...

Why is an error popping up when the import has already been executed successfully?

Description When attempting to execute my code, I encountered an issue. I made several changes to my tsconfig in hopes of resolving it, but now I can't remember what modifications I made. Any insights on this matter would be greatly appreciated! The ...

Select material with name attribute

Currently, I am in the process of converting a simple form from Bootstrap to Material design. The challenge lies in the fact that despite utilizing Angular 6, the form is submitted in an old-fashioned manner without utilizing Angular forms. <form metho ...

Is there a way to modify a single object within an array?

Here is the HTML representation of my data: https://i.sstatic.net/VbKQ4.png page.html <ul id="elements"> <li *ngFor="let elem of fetchdata" (click)="log(elem)"> {{elem.title}} {{elem.description}} </li> ...

Managing the closest element depending on the selected option in Angular 5

My task involves accessing the nearest element of a dropdown. The HTML below includes multiple dropdowns and input boxes. When selecting options from the dropdown, I need to enable or disable the input box closest to it. <div class="form-block" *ngFor= ...

How to eliminate subdomains from a string using TypeScript

I am working with a string in TypeScript that follows the format subdomain.domain.com. My goal is to extract just the domain part of the string. For example, subdomain.domain.com should become domain.com. It's important to note that the 'subdoma ...

The issue with sorting in Angular 8 mat tables persists when dealing with multiple tables

As a newcomer to Angular, I am still learning and have encountered an issue with sorting in the mat table. I have multiple tables on one page, each separated by a mat tab. The problem is that sorting only works on the first table ("crane master list") in t ...

Combining Java with Node.js modules

I'm interested in incorporating Angular2 as the client side framework and Java as the server side. However, I am unfamiliar with how to integrate Angular2 into a Java project. Is it advisable to initialize the NPM system within the Java project and in ...

Setting an attribute with brackets in the name of a checkbox component within Ionic 2 / Angular 2: A guide

Is there a way to apply custom-defined colors to checkboxes in app.variables.scss based on the boolean value of a variable? It's simple for buttons: <button [class.button-customcolor]="variable" [class.button-defaultcolor]="!variable" (click)=what ...

Conversations with Dialogflow and Express: Enhancing Fulfilment

I'm facing a challenge with receiving responses from dialogflow, even though other express calls are functioning properly. I believe the issue lies within the agents, but I am unsure of the specific problem or how to resolve it. That's why I hav ...

Vue.js: Resolving the "Unknown Custom Element" Issue with Hot Module Replacement

I have a good understanding of component registration, but I am encountering a challenging issue: Vue.js component Unknown custom element Unknown custom element when nesting components in Vue.js The Issue at Hand While using the development server, I ...

Struggling to fetch information with Angular HttpClient from an API that sends back a JSON response with an array

As a beginner in Ionic and Angular, I am attempting to call an API and then showcase the team names within the template of my project. Despite following numerous tutorials and videos, I seem to be stuck as the JSON response returns an object with results f ...

Getting the subclass type dynamically within a method of an inherited class in TypeScript

I am working with a class structure. class Node { children: Node[]; } This class is inherited by various other classes. class Block extends Node { // ... } In each of the inherited classes, I want to include a function named replaceChild: const b ...

The interruption function on one idle instance is failing to work due to a timeout occurring on another idle instance

Currently, I'm utilizing "@ng-idle/core": "~11.1.0" in an Angular 13 application. In my setup, I have implemented two idle instances - one for automatic logout and another for a screensaver feature. An issue arises when the screensaver is active and ...

Function Type Mapping

I am in the process of creating a function type that is based on an existing utility type defining a mapping between keys and types: type TypeMap = { a: A; b: B; } The goal is to construct a multi-signature function type where the key is used as a ...

After transitioning to standalone mode, Angular is unable to access the component before it has been

After diligently following the 3 steps to convert everything to standalone, all seemed well. https://angular.io/guide/standalone-migration#migrations-steps I proceeded to manually move the routes into the main.ts and utilized provideRouter as a provider ...

Step-by-step guide to designing a leaflet map using Angular Formly

I am faced with a challenge to incorporate a leaflet map into an angular form using formly, and being new to this formly framework is making it difficult for me. Previously, I was able to integrate the map with regular HTML in angular as shown below: map ...

What is the best way to utilize *ngSwitchWhen in a TypeScript environment?

I am currently working with Ionic2 and Angular2 and encountering an issue while trying to implement a segment using ngSwitchWhen. Unfortunately, the functionality is not working as expected and I am receiving an error message. How can I resolve this issue ...