Increment object property within an array

Asked

Viewed 508 times

0

I do not know what is the best way to implement this, I am trying with switch without success... By clicking the button, I want to increment the property "Qtd";

choice=[
  {"id":"1","name":"PRODUTO1","qtd":"0"},
  {"id":"2","name":"PRODUTO2","qtd":"0"},
  {"id":"3","name":"PRODUTO3","qtd":"0"},  
];

addQtd(id){
    switch(id){
      case '1':
      this.choice[0].qtd++;
      break;
      case '2':
      this.choice[1].qtd++;
      break;
      case '3':
      this.choice[2].qtd++;
      break;
    }
  }
<div *ngFor="let item of choice">
  <button (click)="addQtd(item.id)">Add</button>
</div>

1 answer

1


You can do as follows and eliminate the function addQtd:

<ion-item *ngFor="let item of choice">
  <button ion-button (click)="item.qtd = item.qtd + 1">Add</button>
  <p>{{item.qtd}}</p> <!-- so para mostrar na tela, pode retirar -->
</ion-item>

Another thing is that your property qtd is set as string, you would not be able to increment by adding a number to a string, if that amount comes from a server as string, do not forget to parse the number using Number(variavelQtd). Staying then {..., qtd: Number(variavelQtd)}.

But if you want to have a control over your file . ts can do so:

HTML:

<ion-item *ngFor="let item of choice; let i = index"> <!-- pega o index do item no ngFor -->
  <button ion-button (click)="addQtd(i)">Add</button>
</ion-item>

In your . ts:

addQtd(index){
  this.choices[index].qtd = this.choices[index].qtd + 1;
}

I hope it helps you :D

Browser other questions tagged

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