valdimar
valdimar

Reputation: 3

Relevant item not removing Angular 12

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>

List items

I'm using *ngFor loop to get my items. I didn't put that code here.

Upvotes: 0

Views: 247

Answers (2)

Mike Hanson
Mike Hanson

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

tmsbrndz
tmsbrndz

Reputation: 1347

  1. If you pass negative value to splice the function will remove element(s) from the end.

  2. 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

Related Questions