我正在尝试基于index
删除数组中的特定项目。目前,我在删除数组的第一个和最后一个元素时遇到问题。当我尝试删除最后一个元素时,第一个元素将被删除,反之亦然。
这里是我的代码摘录
HTML
<div *ngFor="let item of itemsList.slice().reverse(); index as i">
<ion-item>{{item.name}} <button (click)="deleteItem(i)">Delete</button></ion-item>
</div>
TS
itemsList = [{
name: 'Item 0'
}];
count = 0;
constructor() {}
addItem() {
this.count += 1
this.itemsList.unshift({
name: `Item ${this.count}`
})
}
deleteItem(index) {
console.log('Delete ', this.itemsList[index].name)
this.itemsList.splice(index, 1)
}
我使用StackBlitz创建了working example。谁能帮忙吗?
在您的接头中使用length - index - 1
以获取正常数组的正确索引。
this.itemsList.splice(this.itemsList.length - index -1, 1)
我想不出您为什么不这样编码的任何原因:
(click)="deleteItem(item)"
这实际上是编写代码的更好的方法。