I am saving a product to localStorage and I need to delete the item from localStorage. I am using
and I get the argument to the function from
<tr *ngFor="let item of items; let i = index">
<button type="button" (click)="deleteItem(i)">X</button></td>
This isn’t working. The product is still in localStorage after executing the above code.
But you’re removing the item after storing it. The correct way should be:
- Remove item from array.
- Remove the item from local storage.
- Re-add the item to local storage.
Step 2 is redundant though, since
setItem would replace the contents of the element.
You’re storing the entire array as a different index on the
localStorage. If you take a look at the local storage manager on your developer tools (F12, usually), you should see something like this:
And I don’t know if that’s what you really want, but seems like a bug.
Hello! You made a slight mistake in your code. I feel this might work.
The first line of code removes the item from local storage, however you did not remove the item “i” from the items array before re-adding it to the local storage. The “i” is still added on line three , because you didn’t call the splice method on the items array before setting it in the local strorage