3

Maybe simple but, I am trying to delete item from an array of objects in Angular, But my current code only returns an undefined in the console as i'm sure it's not finding the right index value. It is also for a Kendo Grid. So I need to Splice based on what the user clicks, not a specific id. Link to demo: https://stackblitz.com/edit/angular-fl5jde-xbsuno

data structure is:

export const data = [
  {
    id: 1,
    name: "Element 1"
  },
{
    id: 2,
    name: "Element 2"
  },
{
    id: 3,
    name: "Element 3"
  },
];

ts file

  public gridData: any[] = data;

  public removeItem(id) {
    let index = data.findIndex(e => e.id === id);
    if (index !== -1) {
      data.splice(index, 1);
    }
    console.log(id)
  }
Giannis
  • 1,400
  • 1
  • 8
  • 22
Sole
  • 2,004
  • 4
  • 30
  • 52
  • Does this answer your question? [How can I remove a specific item from an array?](https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array) – The Fabio Oct 29 '20 at 12:00
  • So It kind of does, I can understand the concept, where I need to find the Index value and splice based on that, but the example you pointed to shows if the index value was '5' and splice on that, where as I need to splice based on what the user clicks – Sole Oct 29 '20 at 12:02
  • 1
    Can you please create the same issue in a sample Stackbliz project and provide a link so that it would be helpful to answer ? – SaiSurya Oct 29 '20 at 12:09
  • 2
    Updated the link in the question – Sole Oct 29 '20 at 12:11

3 Answers3

3

The actual problem is that you pass nothing to removeItem. So, in your html I just wrote removeItem(dataItem) instead of removeItem(id). In the ts the change is let index = data.findIndex(e => e.id === dataItem.id);.

Please check the updated https://stackblitz.com/edit/angular-fl5jde-3pb7ef?file=app/app.component.ts

Giannis
  • 1,400
  • 1
  • 8
  • 22
3

You need to pass the dataItem, like this:

<button
   kendoButton
   look="flat"
   [icon]="'delete'"
   (click)="removeItem(dataItem)"
 >
</button>

And then remove from this.gridData.

.ts

 public removeItem({id}) {
    this.gridData = data.filter(e => e.id !== id);
  }
lissettdm
  • 7,119
  • 1
  • 4
  • 23
1

You can use filter, which is a JavaScript method:

  public removeItem(id) {
    this.gridData = this.gridData.filter(el => el.id != id)
    console.log(this.gridData)
  }

checkout the documentation for filter

checkout the Live demo

Elmehdi
  • 1,065
  • 2
  • 7
  • 19