Skip to content
Advertisement

update the quantity without creating a new row with angular as simply as possible

I try to do a shopping cart each time I add the same item it creates a new line for me, I would like to update the Quantity, do I have to make a loop that goes through an array?

ts.file

  productList = [
    { id: 1, name: 'Louis Vuis', price: 10, qtn: 1 },
    { id: 2, name: 'shubert helmet', price: 20, qtn: 1 },
  ];

  productArray: any = [];

  add(product) {
    this.productArray.push(product);
  }

  inc(added) {
    added.qtn = added.qtn + 1;
  }

  dec(added) {
    if (added.qtn != 1)
      added.qtn -= 1;
  }

  remove(id) {
    this.productArray.splice(id, 1);
  }
}

html

        <div class="card" *ngFor="let product of productList">
            <h1>{{product.name}}</h1>
            <p class="price">{{product.price | currency: 'USD'}}</p>
            <p><button (click)="add(product)">Add to Cart</button></p>

                        <th>product</th>
                        <th>price</th>
                        <th>Quantity</th>
                        <th>Delete</th>
                        <th>total</th>
                    </tr>
                </thead>
                <tbody *ngFor="let added of productArray">
                    <tr>
                        <td>{{added.name}}</td>
                        <td>{{added.price | currency: 'USD'}}</td>
                        <td class="increment">
                            <button (click)="dec(added)">-</button>
                            <span>{{added.qtn}}</span>
                            <button (click)="inc(added)">+</button>
                        </td>
                        <td (click)="remove()"><strong class="remove">X</strong></td>

Advertisement

Answer

You can change your add(product) to:

  add(product, idx) {
    const found = this.productArray.find(
      item => JSON.stringify(item) === JSON.stringify(product)
    );
    if (found) {
      this.productArray[idx].qtn++;
    } else {
      this.productArray.push(product);
    }
  }

Here it will search for a similar product (I dont know which was the unicity criteria, so I compared the whole object with the whole new added one), If it’s found, it would update the quantity, else it push a new product.

And the HTML part:

<div class="card" *ngFor="let product of productList; let idx = index"> // <-- here
    <h1>{{product.name}}</h1>
    <p class="price">{{product.price | currency: 'USD'}}</p>
    <p><button (click)="add(product, idx)">Add to Cart</button></p> // <-- & here 

DEMO

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement