Delete item from an Inioc 2 array

Asked

Viewed 673 times

2

I’m having a hard time understanding how splice() works. I need to delete items from an array when I click on (x), e.g.:

<ion-item *ngFor="let item of data">
  <ion-grid>
    <ion-row>
      <ion-col width-50>
        {{item.nameFruit}}
      </ion-col>
      <ion-col width-50 text-right (click)="delItem(item)">
        X
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-item>

Typescript:

delItem(id){ let elemento = this.data.splice(0,id); }

1 answer

3


splice accepts the start index in the first argument and the number of elements to remove in the second argument. In your case it should be .splice(index, 1), which in practice is:

delItem(item){
   const index = this.data.indexOf(item);
   const elementoRemovido = this.data.splice(index, 1);
   // aqui podes fazer algo com o item removido
   // a array modifica-se a si própria com o splice
}

More about .splice() in MDN (in English)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.