Delete item from an Inioc array 2

2

I'm having a hard time understanding how the splice () method works. I need to delete items from an array, when I click on (x), eg:

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

    
asked by anonymous 25.04.2017 / 12:03

1 answer

3

The 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() na MDN     

25.04.2017 / 12:13