我正在尝试根据Angular 2中的一个属性从对象数组中删除一个元素。
如何实现removeItem
函数,以便根据其id属性从数组中删除comment
对象,从而将其从列表中删除?
这是HTML模板(所有评论都有ngFor
循环):
<div *ngFor="let comment of list">
<button (click)="removeItem({{comment.id}})">delete</button>
(... comment.... )
....
这里是Angular 2代码:
export class Comments {
list =
[new Comment(1, "text one", "koby", new Date("2015.01.02")),
new Comment(2, "text two", "adim", new Date("2017.02.02")),
new Comment(6, "text six", "asaf", new Date("2016.11.04"))
];
addItem(val: string) {
this.list.push(new Comment(3, "kokoko", "kobydo", new Date("2015.01.02")));
}
removeItem(id: number) {
// How do I remove it from the array ?
}
}
export class Comment {
constructor(
public id: number,
public text: string,
public creator: string,
public date: Date
) { }
}
答案 0 :(得分:10)
你可以.filter()
:
removeItem(id: int) {
this.list = this.list.filter(item => item.id !== id);
}