Delete Item from Array in Angular at Index value

Viewed 1202

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)
  }
3 Answers

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

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

Related