我的删除方法是拼接出数组中的最后一项,而不是所选项目

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

我正在尝试使用 splice 方法从我的 angular 2 应用程序的数组中删除一个项目。但是现在,当我将鼠标悬停在某个项目的垃圾图标上并单击它时,数组中的最后一项被删除,而不是我正在单击的那个。我需要在我的代码中进行哪些调整才能删除当前单击的项目,而不是数组中的最后一项?

这是我的组件信息:

  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);
  }

这是我的组件的相关代码 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>

好像找不到this.zipcode.
如果 this.zipcodes.indexOf(this.zipcode) returns -1 (未找到)则调用:

this.zipcodes.splice(-1, 1)

将始终删除 return 最后一项。

穆里克,

看起来 "this.zipcode" 可能不是您要删除的索引。

考虑像这样传递要删除的索引:

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

这会将索引传递给您的方法,现在是:

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

您应该将邮政编码传递给删除方法

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

然后在你的模板中

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