Search code examples
javascripthtmlangulartypescriptangular7

Minus quantity base on id


Actually I want to minus quantity based on id .When user click button on 'A', just qunatity of 'A' should get reduced by 1. This Demo code stackblitz

HTML

<p *ngFor="let item of arrayOfArray"> 
  Name: {{item.name}} Quantity: {{item.quantity - currentIndex}} <button (click)="addItem(item)">minus Quantity</button>
</p>

Component

public currentIndex = 0;
  arrayOfArray = [
    {id: '1', name: 'A', quantity: '12'}, 
    {id: '2', name: 'B', quantity: '29'},
    {id: '3', name: 'C', quantity: '21'}, 
    {id: '4', name: 'D', quantity: '11'}
  ]

  addItem(val){
    if(val.id){
      this.currentIndex += 1;
    }
  }

Solution

  • You are doing it wrong . check this demo code

    for html

    <p *ngFor="let item of arrayOfArray"> 
      Name: {{item.name}} Quantity: {{item.quantity}}
      <button (click)="minusItem(item)">minus Quantity</button>
    </p>
    
      minusItem(val){
        if(val.id){
          for (let ele of this.arrayOfArray) {
             if (ele.id === val.id){
              ele.quantity--;
              break
            }
          }
        }
      }