Drew13
Drew13

Reputation: 1371

Permanently change array even with page refresh

I'm coding using Angular 2 (Typescript) and on my webpage I have different forms with inputs and when I submit those forms they trigger their own function that adds a new instance of an object based on the inputs to an array, which is then reflected in a table on the page that is generated from said array. How can I permanently save those changes in the array after the page is refreshed. The array DPS is imported from another directory. The submitForm function is in a Typescript file of a component that's separate from the Typescript and component of the main page (the HTML and rest of the Typescript). Below, you'll see my use of onload="myFunction()" for my overall container on the main page and the myFunction() function as well.

Here's the function that adds 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));
}

div for my main page:

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

myFunction():

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

Upvotes: 0

Views: 367

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164307

You can save it in the localStorage:

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

And on page load you can check if you already have it:

let DPS = localStorage.getItem("DPS");
if (DPS) {
    localStorage.removeItem("DPS");
    DPS = JSON.parse(DPS);
    // you have an intance
}

Edit

Seems that there's a library for local storage in angular2: angular2-localstorage.

Upvotes: 2

Related Questions