Angular 2 - 根据其中一个属性从对象数组中删除元素

Kob*_*uek 5 angular

我正在尝试根据Angular 2中的一个属性从对象数组中删除一个元素.

我如何实现该removeItem函数,以便它将根据其id属性comment从数组中删除该对象,从而将其从列表中删除?

这是HTML模板(包含ngFor所有注释的循环):

<div *ngFor="let comment of list">
     <button (click)="removeItem({{comment.id}})">delete</button>
     (... comment.... )
     ....
Run Code Online (Sandbox Code Playgroud)

这里是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
    ) { }

}
Run Code Online (Sandbox Code Playgroud)

Jai*_*Jai 11

你可以.filter():

removeItem(id: int) {
    this.list = this.list.filter(item => item.id !== id);
}
Run Code Online (Sandbox Code Playgroud)