Persist changes to array even after refreshing the page

Currently, I am utilizing Angular 2 (Typescript) to code my webpage, which features various forms with inputs. Upon submitting these forms, they each trigger a function that adds a new instance of an object based on the inputs to an array. This array is then used to generate a table on the page. My concern is how to permanently save these changes in the array even after the page is refreshed. The array labeled DPS is imported from another directory. Furthermore, the submitForm function resides within a separate Typescript file of a component distinct from the main page's HTML and remaining Typescript. Below, you will find my implementation of onload="myFunction()" for the overall container section on the main page, along with the accompanying myFunction() function.

Below is the function responsible for adding to the array:

submitForm(value: any){
  var val1 = String((<HTMLInputElement>document.getElementById("dataPoint")).value);
  var val2 = String((<HTMLInputElement>document.getElementById("ICCP")).value);
  var val3 = String((<HTMLInputElement>document.getElementById("startDate")).value);
  var val4 = String((<HTMLInputElement>document.getElementById("endDate")).value);
  let blah = new DataTable(val1,val2,val3,val4);
  DPS.push(blah);
  localStorage.setItem("DPS", JSON.stringify(DPS));
}

Main page div element:

<div class="container-fluid page" onload="myFunction()">

Implementation of myFunction():

 myFunction(){
   let DPS = localStorage.getItem("DPS");
   if (DPS) {
     localStorage.removeItem("DPS");
     DPS = JSON.parse(DPS);
    }
  }

Answer №1

If you want to store data for later use, consider saving it using the localStorage:

...
DPS.push(blah);
localStorage.setItem("DPS", JSON.stringfy(DPS));

When the page loads, you can then check if the data is already stored:

let DPS = localStorage.getItem("DPS");
if (DPS) {
    localStorage.removeItem("DPS");
    DPS = JSON.parse(DPS);
    // The data is available
}

Update

A useful library for handling local storage in Angular 2 is available: angular2-localstorage.

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

I am experiencing challenges with utilizing the fetch() function and am unable to retrieve the data

I'm currently struggling with integrating Google's reCaptchaV3 into my website, particularly when using the fetch() function. Here is the code snippet I have developed so far: function sendData(name, email, captcha) { const info = JSON.stri ...

Utilizing the power of Vue 2 and NuxtJS to effortlessly customize the appearance of child components

I am currently working on a Nuxt.js project (still using Vue 2) that consists of two components. I am trying to override the child style with the parent's style, but the ::v-deep pseudo selector doesn't seem to be effective. Regardless of my eff ...

Is it possible to measure the CPU utilization in a TypeScript application programmatically?

Is there a method to calculate CPU usage as a percentage and record it in a file every 20 milliseconds? I'm interested in exploring different approaches for accomplishing this task. Your insights would be greatly appreciated! I've come across so ...

Tips for converting a particular subset of a byte array into a character array

I have a task where I need to extract a portion of a byte array and convert it into a char array. For example: Given the byte array: byte[] b = {4, 3, 2, 1, 5, 0, 0, 0}; I want to extract the elements at positions 2 to 5 and create a char array like th ...

Is it possible to add a div element to a button click event in React?

I am currently developing a hotel reservation web app using React. My goal is to allow users to select the number of rooms, adults, and children for their hotel reservations. The screenshot below illustrates exactly what I have in mind. https://i.sstatic. ...

What is the best way to sort ISO DateTime objects that fall outside of a particular time frame?

I'm currently working on a project that involves a list of objects with properties for startTime and endTime, all in ISO format. Here's a snippet of the list: list = [ { startTime: '2022-06-26T10:00:00.000Z', endTime: '2022- ...

Issue arises when compiling React Redux due to a union type that includes undefined

I am currently in the process of learning how to integrate Redux with React using Typescript. I encountered a compilation error that relates to the type of my store's state, specifically as {posts: PostType[]}. The error message states: Type '{ p ...

What is the best way to write a function that takes a mixin function as input parameter?

In my code, there is a function named Mixin which requires a single argument in the form of a "class factory mixin". For example, let's consider a scenario where I have a class factory mixin function like this: type Constructor<T = any, A extends ...

Issue with AdonisJS Lucid idempotent methods and the updateOrCreateMany() function

Seeking clarification on a 500 error related to a specific attribute in the database while using updateOrCreateMany(), as opposed to no error when using updateOrCreate(). Here is the code snippet for updateOrCreateMany(): const payload = [ { githubI ...

Execute JS function when navigating back in history

I recently came across an article on browser bfcache in Stack Overflow. I decided to test it out on Safari Version 7.0.5 (9537.77.4) and noticed that when I click the back button in history, the JavaScript does not execute. How can I ensure that my JavaS ...

Centralize all form statuses in a single component, conveniently organized into separate tabs

I am working on a component that consists of 2 tabs, each containing a form: tab1.component.ts : ngOnInit() { this.params = getParameters(); } getParameters() { return { text : 'sample' form: { status: this.f ...

Effortlessly glide to the top of the webpage

After dedicating numerous hours to this task and being a newcomer to JavaScript/JQuery, I am still unsure of how to achieve the following: I have implemented a "back to top" anchor link in the footer of my pages that directs users back to the header. I am ...

Issue with input decorator: values are not being passed and are appearing as undefined

My @input decorator in my code isn't fetching values from a model as expected. When I try to log the result, it shows undefined. Let's take a look at the code snippets: Model export interface ExistingSaving { value: number; sourceId: any; ...

Incorporating CASL with the latest version of Angular, version

I'm currently working on implementing CASL into my Angular application, but I'm having trouble understanding how to integrate it. // Login Component ngOnInit() { var jsonBody = {}; jsonBody['email'] = 'peter@klaven'; ...

Javascript lags behind in utilizing Regex compared to PHP

My regex string is used to extract a value from CSS code like this: body { background: #000; } /* drapeDecalage: 10px */ I am trying to parse the commented drapeDecalage value. I have created a regex expression for that: (?<=\/\* drape ...

Is integrating Vuetify with a project template created using vue-cli 3 causing issues when adding script tags to App.vue?

As a Vue beginner, I'm trying to wrap my head around a basic concept. In vue-cli 3, the "App.vue" file serves as the root component with <script> and <style> tags like any other component. However, after adding Vuetify to a project, the Ap ...

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

Leverage the power of JavaScript's Map and Filter functions to manipulate

I have an array with the following elements: arr = ['AD', 'CI', 'AI'] Additionally, I have an object as shown below: { "AD": "Mailing Address", "CI": "Additional Interest", "HO": "Homeowners", "AI": "Additional Int ...

Building a seamless service across all components in Angular4

In every service, there is a need for a shared common service that will only be created once. For example, let's call this common service - export Class CommonService { _commonVar1= ""; _commonVar2= ""; } Now, the instance of the common ...

React Data Filtering Techniques

I'm currently facing an issue with the if statement in my Action component. I'm struggling to figure out how to handle the case when an item is not found in the data from a JSON file. I have a Filtering function in a Context that I am using globa ...