Reputation: 3
Tried to remove an item from the array but it's removing the last index of that array, not the relevant one, below is my code. Ex: if I remove the first item from the list then it's removing the last item from the list.
component.ts code
this.items.splice(this.items.indexOf(id));
html code
<span class="close" style="cursor: pointer;" (click)="removeItems(item.Id)">
<i class="far fa-trash-alt fa-2x" style="color: red;"></i>
</span>
I'm using *ngFor loop to get my items. I didn't put that code here.
Upvotes: 0
Views: 247
Reputation: 306
If items is a collection of objects then using indexOf with just the id is likely to return -1 every time, which would explain why the last item is being removed.
You would probably need something like
const itemToRemove = this.items.findIndex(i => i.id === id);
if(itemToRemove >= 0) {
this.items.splice(itemToRemove, 1);
}
Upvotes: 0
Reputation: 1347
If you pass negative value to splice
the function will remove element(s) from the end.
You need to pass number of items to be removed. So you are looking for this : this.items.splice(this.items.indexOf(id), 1);
Upvotes: 1