What is the best way to access a specific object value in Angular's Local Storage?

In my Angular application, there is a field called maan in the database. The value of this field is displayed twice on the frontend - one static and the other dynamic.

To store the dynamic value, I am using Angular Local Storage in the saveChanges function. A new variable is created to hold this value:

var change_single_object = JSON.parse(localStorage.getItem('LikeWhen') || '{}') as LikeWhen
change_single_object.maan= maan; -------> This line tries to access the dynamic value (#term reference in html)

However, the above statement always refers to the static value. How can I resolve this issue?

Interface:

export interface LikeWhen {
    maan: string;  
}

component.ts:

export class RufusComponent { 
  @ViewChild('term') editElem!: ElementRef<HTMLTableDataCellElement>;
  
saveChanges(rec: LikeWhen, new_value: HTMLTableDataCellElement) {
 localStorage.setItem('LikeWhen', JSON.stringify(rec));
 var change_single_object = JSON.parse(localStorage.getItem('LikeWhen') || '{}') as LikeWhen
 change_single_object.maan= maan;-------------> PROBLEM (Refers to static value)

 localStorage.setItem('LikeWhen', JSON.stringify(change_single_object));
}
}

.html:

// --------static value
 <mat-list-item>Static Value Amazon</mat-list-item>
            <mat-list>{{latestData.maan}}</mat-list>
            <mat-divider></mat-divider>

// -------dynamic value
            <mat-list-item>Dynamic Value</mat-list-item>
            <mat-list class="textFields">
                <table>
                    <tr>
                        <td [innerHTML]='latestData.replaceHTML' #term></td>
                    </tr>
                </table>                
            </mat-list>

//button
<button mat-raised-button type='button' [disabled]='confirmDisabled' (click)='saveChanges(latestData, term)'>Confirm

Answer №1

If you want to store data locally, you can utilize the setItem and getItem methods as shown below:

localStorage.setItem('myDog', 'Rex');

const dog = localStorage.getItem('myDog');

For more information on this topic, you can refer to: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

To update data dynamically based on certain events, you can employ Angular services and rxjs subject like this:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {
  localStorage: Storage;

  changes$ = new Subject();

  constructor() {
    this.localStorage   = window.localStorage;
  }

  get(key: string): any {
    if (this.isLocalStorageSupported) {
      return JSON.parse(this.localStorage.getItem(key));
    }

    return null;
  }

  set(key: string, value: any): boolean {
    if (this.isLocalStorageSupported) {
      this.localStorage.setItem(key, JSON.stringify(value));
      this.changes$.next({
        type: 'set',
        key,
        value
      });
      return true;
    }

    return false;
  }

  remove(key: string): boolean {
    if (this.isLocalStorageSupported) {
      this.localStorage.removeItem(key);
      this.changes$.next({
        type: 'remove',
        key
      });
      return true;
    }

    return false;
  }

  get isLocalStorageSupported(): boolean {
    return !!this.localStorage
  }
}

For further insights, visit:

Answer №2

By utilizing JSON.parse(), a fresh JSON object is generated from text, indicating it's distinct from the initial data reference.

To implement this in Angular successfully, you must transmit the original referenced data to the dynamic display or component.

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

Unraveling in jQuery

Struggling to properly handle the data being returned by JQuery from an API call. Currently encountering an error in the process. Is it possible to iterate through data using a JQuery loop like this? $.each(data.results, function (i, item) { // attemptin ...

When the user clicks, the template data should be displayed on the current page

I need help with rendering data from a template on the same HTML page. I want to hide the data when the back button is clicked and show it when the view button is clicked. Here is my code: <h2>Saved Deals</h2> <p>This includes deals wh ...

What is causing the Angular HTTP Post method error "Property 'post' is undefined"?

Encountering an error while using Angular's HTTP Post method: Cannot read property 'post' of undefined. I am attempting to send my first HTTP POST request, but it is not functioning as expected. export class RegisterComponent impleme ...

Stop the setTimeout function after redirecting in the controller

I am experiencing an issue with my AJAX call as it keeps triggering my controller repeatedly. AJAX function <script type="text/javascript> var stopTime =0; var scoreCheck = function () { $.ajax({ url: "<?php echo 'http:// ...

What is the best way to showcase a bootstrap dropdown within a limited height container while keeping the overflow hidden?

I have developed a collapsible toolbar that features a bootstrap dropdown element. The challenge I am facing is maintaining a fixed height for the toolbar while ensuring that any content exceeding this height is hidden, with the exception of popups. To add ...

Utilizing a single AWS IoT connection for every component in Angular 6: A complete guide

In my Angular 6 project, I integrated AWS IoT for chat and notification functionalities. Initially, I was connecting to AWS IoT from multiple components like the header, chat, and home components. However, I now want to streamline the process by establishi ...

Incorporate a dropdown feature into a data table column

Currently, I am using PrimeNG and Angular 2 to create a web application that includes a data table. Everything is functioning correctly up to this point. However, I would like to incorporate a dropdown component within a data cell. This means that the p-co ...

Discover the magic of using jQuery's .map() method with

$(function() { $('input[type=checkbox]:checked').map(function() { alert($("#chk_option").val()); $("#chk_option").val(this.value); }).get(); }); HTML code <div> <center> <form id="form_tarif" class="form-horizo ...

Steps for showing the text entered into the input box as soon as it is typed:

I am attempting to create a feature where text is displayed as soon as it is typed into an input box. Currently, my JavaScript function is not working at all. I simply want the function to display text when it is typed into or erased in the text boxes. & ...

What is the best way to simulate fetch in Redux Async Actions?

When writing tests in the Redux Writing Tests section, how does store.dispatch(actions.fetchTodos()) not trigger the fetch method when store.dispatch is directly calling actions.fetchTodos? The issue arises when trying to run similar code and encountering ...

How can we use the jQuery toggle function to hide and show elements based on

When using the toggle function, I have noticed that it takes a considerable amount of time to load. As a solution, I attempted to include a loading image while the content loads; however, the image does not appear when the .showall is activated. This iss ...

The Angular modal service is failing to show up on the screen

I am having trouble implementing the angular modal service in my web application. When I click on the button, the modal does not appear. Can someone help me figure out what I am doing wrong? Builder View <div ng-controller="BuilderController as vm"> ...

Activate the submission button only when all the necessary fields have been completed

I am currently working on a form that consists of 3 fields: email_from, email_subject, and an editor. The editor is built using draftjs. I am facing an issue with enabling the submit button only when all the fields are filled without any errors. Below is ...

ngSrc must be a fixed string

When working with Angular 17, the code I use is: <img [ngSrc]="profilePicture" fill="" priority="" alt="Profile Picture"> However, in the Google Chrome browser, a warning message pops up: NG02964: The NgOpti ...

Utilizing PHP Variables in Jquery Ajax Success Response

I have a webpage that displays a list of routes. When a user clicks on a route, an AJAX request is sent to save the selected route in the database. On the same page, in a different tab, I am running a query to fetch related information about the selected ...

The output of jQuery('body').text() varies depending on the browser being used

Here is the setup of my HTML code: <html> <head> <title>Test</title> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function initialize() { var ...

MERN stack does not have a defined onClick function

I am developing a website for college registration, and I encountered an issue while trying to create a feature that allows students to select a major and view all the associated courses. I made a list of majors with buttons next to them, but whenever I at ...

JavaScript's asynchronous callbacks

As a PHP developer delving into the world of NodeJS, I find myself struggling to fully grasp the concept of asynchrony in JavaScript/Node. Consider this example with ExpressJS: router.get('/:id', function (req, res, next) { var id = req.par ...

Navigating the application of interfaces within React using TypeScript

As a React newcomer, I am currently exploring TypeScript integration in my project. One concept that has me stumped is interfaces - why are they necessary in React development? Any insights or guidance would be greatly appreciated. ...

Exclude extraneous keys from union type definition

Working on a call interface that outlines its arguments using specific properties and combined variants. type P1 = {prop1: number} type P2 = {prop2: number} type U1 = {u1: string} type U2 = {u2: number} export type Args = P1 & P2 & (U1 | U2) In th ...