Increase property of an object within an array

0

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

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>
    
asked by anonymous 27.04.2017 / 21:09

1 answer

1

You can do as follows and delete 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 its qtd property is set to string, you would not be able to increment by adding a number to a string, if that amount comes from a server as a string, be sure to give a parse for number using% with%. Then getting Number(variavelQtd) .

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

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: D

    
27.04.2017 / 22:04