Angular 2 - Remove an element from an array of objects according to one of its properties

I am trying to remove an element from an array of objects according to one of its properties, in Angular 2.

How can I implement a function removeItemto remove an object commentfrom an array according to the id property and remove it from the list?

Here's the HTML template (loops with ngForfor all comments):

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

Here's Angular 2 code:

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
    ) { }

}
+4
source share
1 answer

You can .filter()it:

removeItem(id: int) {
    this.list = this.list.filter(item => item.id !== id);
}
+8
source

Source: https://habr.com/ru/post/1670407/


All Articles