我试图通过利用拼接方法从我的角度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);
}
这是我的组件模板/视图中的相关代码:
<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>
答案 0 :(得分:3)
您应该将zipcode传递给删除方法
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>
答案 1 :(得分:2)
似乎无法找到this.zipcode
如果this.zipcodes.indexOf(this.zipcode)
返回-1
(未找到),则调用:
this.zipcodes.splice(-1, 1)
将始终删除并返回最后一项。
答案 2 :(得分:1)
Muirik,
看起来“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);
}