我正在使用Angular 5,我创建了一个从数组中删除对象的函数:
这是数据:
this.widgets = [
{ id: 1, title: 'Object 1', config: { row: 1, col: 1, sizex: 1 }}
{ id: 2, title: 'Object 2', config: { row: 1, col: 2, sizex: 1 }}
];
这是功能:
removeObj(id) {
this.widgets.splice( this.widgets.indexOf(id), 1 );
}
这在我的组件的html部分:
<div *ngFor="let widget of widgets" [(ngWidget)]="widget.config">
<button (click)="removeObj(widget.id)">X</button>
<div class="title">{{widget.title}}</div>
<p>{{widget.id}}</p>
</div>
我需要它只是删除所选对象,但它只是删除第一个对象。
我怎样才能解决这个问题?
尝试使用array.prototype.filter:
this.widgets = [
{ id: 1, title: 'Object 1', config: { row: 1, col: 1, sizex: 1 }}
{ id: 2, title: 'Object 2', config: { row: 1, col: 2, sizex: 1 }}
];
removeObj(id) {
this.widgets = this.widgets.filter(widget => widget.id !== id);
}
在removeObj
函数中,您必须搜索参数中传递的id。你不能只使用indexOf
来获取索引。
removeObj(id) {
var index = -1;
this.widgets.forEach((widget, i) => {
if(widget.id === id) {
index= i;
return;
}
});
this.widgets.splice( this.widgets.indexOf(index), 1 );
}
您还可以尝试以下一行代码
delete this.widgets[this.widget.indexOf(id)];
ID是您的对象属性,而不是数组索引。你可以这样做:
<div *ngFor="let widget of widgets; let i = index" [(ngWidget)]="widget.config">
<button (click)="removeObj(i)">X</button>
<div class="title">{{widget.title}}</div>
<p>{{widget.id}}</p>
</div>
尝试在拼接前映射数组:
removeObj(id) {
widgets.splice((widgets.map(o => o.id)).indexOf(id) , 1);
}
试试这个
removeObj(id) {
let index = this.widgets.findIndex(function (o) {
return o.id === id;
})
this.widgets.splice(index, 1);
}