How do I remove a specific object from my localStorage array in Angular?

Currently, I am storing and retrieving form values from localStorage. When displaying the data, I want to be able to remove a specific object that is clicked on. The issue is that my current code removes all the data instead of just the selected object. Below is an example of the policy value:

"beneficiaryInfo":[
      {
         "name":"test",
         "surname":"test2",
         "personalNumber":"02027041738",
         "phone":"5685522555"
      },
      {
         "name":"test3",
         "surname":"test5",
         "personalNumber":"02027041738",
         "phone":"5685522555"
      }
   ]

.html

<div *ngFor="let u of user.beneficiaryInfo">
            <span>
              {{u.name}} {{u.surname}}
            </span>
    <div class="del" (click)="del()">
    </div>
  </div>

.ts

get user(): any {
    return JSON.parse(localStorage.getItem('policy'));
}

del() {
    updateLocalStorage('policy', removeValueFromObject<Policy>(getFromLocalStorage<Policy>('policy'), 'beneficiaryInfo'));
}

helpers.ts

export const updateLocalStorage = (storageKey: string, object: object) =>
    localStorage.setItem(storageKey, JSON.stringify(object));

export function getFromLocalStorage<T>(storageKey: string): T {
    return JSON.parse(localStorage.getItem(storageKey));
}
export function removeValueFromObject<T>(object: T, key: string): T {
    delete object[key];
    return object;
}

Answer №1

The `beneficiaryInfo` array is completely removed by the `del` function. To remove a specific object from the array, you must specify the index or id.

In your template, declare the index and pass it as an argument to your delete method in order to remove the object at that index from the list.

    <div *ngFor="let u of user.beneficiaryInfo; index as i">
        <span> {{ u.name }} {{ u.surname }} </span>
        <div class="del" (click)="del(i)"></div>
    </div>

In the controller, the delete method can be implemented as follows:

    del(index: number) {
        const data = JSON.parse(localStorage.getItem('policy') as string);

        const newData = {
            ...data,
            beneficiaryInfo: data.beneficiaryInfo.filter((_: any, i: number) => i !== index)
        };

        localStorage.setItem('policy', JSON.stringify(newData));
    }

UPDATE

To remove the `beneficiaryInfo` property if the list is empty, a check needs to be performed and the property should be removed using destructuring:

    del(index: number) {
        const data = JSON.parse(localStorage.getItem('policy') as string);

        const beneficiaryInfo = data.beneficiaryInfo.filter((_: any, i: number) => i !== index);

        let newData: MyDataType;

        if (beneficiaryInfo.length > 0) {
            newData = { ...data, beneficiaryInfo };
        } else {
            const { beneficiaryInfo, ...partialData } = data;
            newData = partialData;
        }

        localStorage.setItem('policy', JSON.stringify(newData));
    }

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

What is the best way to include a button at the bottom of a Material UI table?

I've been working with Material UI in React TypeScript and I'm having trouble adding a button at the bottom that leads to a form. Despite my attempts, I haven't been successful. Can someone please help me with this? I just need a simple butt ...

Is there a method to dynamically incorporate takeUntil into observables through programming?

I'm working on creating an AutoUnsubscribe class that will handle all subscriptions used in components with the @AutoUnsubscribe decorator and unsubscribe them in ngOnDestroy. I have attempted to retrieve all variables and add takeUntil, which somewh ...

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

Having difficulty implementing Angular 4 redirection for transitioning from old hash URLs to new non-hash URLs

In our single page application, we originally had a simple tab structure where each tab click led to a corresponding #url. Examples: , After transitioning to Angular 4, the urls no longer contain hash symbols. They now look like this: , I have added the ...

Customizing the Android Back Button behavior in NativeScript for a single specific page

I am currently using NativeScript version 5.2.4 along with TypeScript. My goal is to disable the back button functionality in one specific page only, but I'm facing an issue where it also disables the back button behavior for child pages. Below is the ...

Generating a type definition from a JavaScript file

Looking to convert a .js file to a d.ts file, I've noticed that most resources on this topic are from 2 years ago How do you produce a .d.ts "typings" definition file from an existing JavaScript library? My question is, after 2 years, is there a simp ...

Looking for a specific phrase in the data entered by the user

I am dealing with data in ckeditor that looks like this: <p>test 1</p> <p>test 2</p> <p><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICw ...

The function rowSelected was triggered twice, once for being selected and once for being deselected

Utilizing Ag-Grid in my grid has been smooth sailing so far, but now I find myself needing to implement a click event on a row under certain conditions (error condition callback). The desired functionality is such that upon the first click on a row, it beh ...

Global registration of router directives with Angular router RC3 is required

I'm trying to avoid registering the Router_Directives for each individual component. Instead, I would like to apply it globally similar to how I did before: import { RouterConfig ,Router, ActivatedRoute, ROUTE_PROVIDERS} from '@angular/router&a ...

Expand row size in grid for certain row and item

For my project, I am utilizing a Grid layout to display 5 items per row. Upon clicking on an item, my goal is to have the item detail enlarge by increasing the size of the HTML element. Is there a CSS trick that allows me to instruct the Grid to expand a ...

Attempting to locate a method to update information post-editing or deletion in angular

Are there any methods similar to notifyDataSetChange() in Android Studio, or functions with similar capabilities? ...

Tips for retrieving refreshed information following modifications via a POST request in Angular 2

I've scoured the web extensively, but I just can't seem to grasp how to retrieve updated data from the database. I'm currently learning Angular 2, and my predicament lies in fetching data from a table named 'branches' using PHP wit ...

Arrange an array of objects by making a nested API call in Angular

My task involves sorting an array of objects based on the response from the first API call in ascending order. The initial API call returns a list of arrays which will be used for the subsequent API call. The first API call fetches something like this: [0 ...

Transforming an Image URL into base64 format using Angular

I'm currently facing difficulty when attempting to convert a specified image URL into base64. In my scenario, I have a string that represents the image's path. var imgUrl = `./assets/logoEmpresas/${empresa.logoUrl}` Is there a way to directly co ...

Display content based on selected option

I am struggling to display a div based on the selection I make. Unfortunately, it's not working as expected. Can anyone offer guidance on how to tackle this issue? <div class ="row"> <div class="form-group col-md-6"> <label for= ...

Guide to Reverting the Two-Way ngModel Binding Data in Angular 2

I am utilizing a form in angular 2 that includes two-way binding data value ([(ngModel)]) to enable both edit and add functionality. When a user selects the edit option on the listing page and modifies the input, the new values automatically appear on the ...

Updating the navigation bar in Node/Angular 2 and displaying the sidebar once the user has logged in

I am facing a challenge with my first project/application built using Angular 2, particularly related to the login functionality. Here is what I expect from the application: Expectations: When I load the login component for the first time, the navbar ...

Eliminate a specific choice from a drop-down menu in an Angular application

I am implementing a feature where clicking on a button adds more select drop downs. I want to ensure that the selected options in these new dropdowns do not duplicate any already chosen options. Below is the code snippet used for the select drop down: < ...

Troubleshooting an Angular application

Just diving into Angular and following along with the tutorial on https://angular.io/tutorial. However, I seem to be facing an issue in Chrome where the const HEROES is not available in my watch list. It keeps showing as "not available". What could be ca ...