5

I'm trying to Remove an element from object array according to one of its properties, in Angular 2.

How can I implement the removeItem function so it will remove the comment object from the array according to its id property and thus remove it from the list ?

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

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

Here the 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
  • You don't need to use the interpolation:(click)="removeItem(comment.id)" Commented Feb 21, 2017 at 12:14
  • @developer033 What do you mean ? Commented Feb 21, 2017 at 12:34
  • It's just a tip because you used interpolation ( {{ }} ): (click)="removeItem({{comment.id}})". In fact, you don't need it. Commented Feb 21, 2017 at 12:37
  • Thanks. I know - Just fixes it to removeItem( entry.id ) - Thank you so much. Have a great day. Commented Feb 21, 2017 at 12:45

1 Answer 1

11

You can .filter() it:

removeItem(id: int) {
    this.list = this.list.filter(item => item.id !== id);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Jai. Have a great day.
You are welcome @KobyDouek. Glad this worked for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.