Muirik
Muirik

Reputation: 6289

My Delete Method is Splicing out the Last Item in My Array, Rather than the Selected Item

I am trying to remove an item from an array in my angular 2 app by utilizing the splice method. But right now, when I hover over the garbage icon for an item and click it, the last item in the array gets deleted, rather than the one I am clicking on. What do I need to adjust in my code to delete the current clicked item, rather than the last item in the array?

Here is my component info:

  zipcodes = [
    { id: 3, zipcode: '75201', city: 'Dallas' },
    { id: 8, zipcode: '75205', city: 'Dallas' },
    { id: 1, zipcode: '77001', city: 'Houston' },
    { id: 2, zipcode: '78703', city: 'Austin' },
  ];

  deleteZip() {
    console.log('Delete zip clicked...');
    this.zipcodes.splice(this.zipcodes.indexOf(this.zipcode), 1);
  }

And here's the relevant code from my component template/view:

<div *ngFor="let zipcode of zipcodes">{{zipcode.zipcode}} -- <span>{{zipcode.city}}</span><span class="delete-option" (click)="deleteZip()"><i class="material-icons">delete</i></span></div>

Upvotes: 0

Views: 708

Answers (3)

Evans M.
Evans M.

Reputation: 1951

You should pass the zipcode to your delete method

deleteZip(zipcode:any) {
    let index = this.zipcodes.indexOf(zipcode);
    if(index >= 0) {
        this.zipcodes.splice(index , 1);
    }
}

Then in you template

<div *ngFor="let zipcode of zipcodes">{{zipcode.zipcode}} -- <span>{{zipcode.city}}</span><span class="delete-option" (click)="deleteZip(zipcode)"><i class="material-icons">delete</i></span></div>

Upvotes: 3

chrispy
chrispy

Reputation: 3612

Muirik,

Looks like the "this.zipcode" might not be the index you want to remove.

Consider passing in the index you want to remove like so:

<div *ngFor="let zipcode of zipcodes; let myIndex=index">{{zipcode.zipcode}} -- <span>{{zipcode.city}}</span><span class="delete-option" (click)="deleteZip(myIndex)"><i class="material-icons">delete</i></span></div>

This passes the index to your method, which would now be:

deleteZip(zipIndex: number) {
    this.zipcodes.splice(zipIndex, 1);
}

Upvotes: 1

Nitzan Tomer
Nitzan Tomer

Reputation: 164217

Seems that it can't find this.zipcode.
If this.zipcodes.indexOf(this.zipcode) returns -1 (not found) then calling:

this.zipcodes.splice(-1, 1)

Will always remove and return the last item.

Upvotes: 2

Related Questions