localStorage data disappears after the page is refreshed

1,835 views
Skip to first unread message

Maureen Moore

unread,
Jun 30, 2020, 5:40:36 PM6/30/20
to Angular and AngularJS discussion
I am using a ControlValueAccessor to change my div tag to a form element and I am using localStorage to set and get my data. I am having the problem that my product_name item isn't being saved and after I refresh the page, the product_name disappears. How can I change my code so that the data persists after a page refresh?

In the HTML template:

<div class="product_name" name="p_name"></div>
<div name="product_name" (click)="add('Bike')" style="cursor:pointer;">Bike</div>


In the controller:

add(product_name){
localStorage
.setItem("product_name", product_name);
(document.querySelector('.product_name') as HTMLElement).innerText = localStorage.getItem("product_name");
}

tha...@rikkeisoft.com

unread,
Jun 30, 2020, 11:04:28 PM6/30/20
to Angular and AngularJS discussion

document.querySelector('.product_name')  return an array, not an object. You can try:
 (document.querySelector('.product_name') as HTMLCollection)[0].innerText = localStorage.getItem("product_name");
Btw, why don't you use product_name instead of localStorage.getItem("product_name") ?

Maureen Moore

unread,
Jul 1, 2020, 7:42:12 AM7/1/20
to Angular and AngularJS discussion
Thank, tha...@rikkeisoft.com I haven't deployed the program to a production server yet so it's re-compiling every time on my localhost when I refresh the page. That's probably why I lose the localStorage.
Reply all
Reply to author
Forward
0 new messages