更新数量而不用 angular 尽可能简单地创建新行

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

每次我添加相同的项目时,我都会尝试做一个购物车,它会为我创建一个新行, 我想更新数量,是否必须创建一个遍历数组的循环?

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>

问题来自:

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

您推送相同的项目并在数组中创建一个新对象。 您可以通过检查此项目是否存在来修复它:

add(product) {
for(let singleProduct of productList){
  if(singleProduct.name === product.name){
   //here you want to only increase the quantity of this product
   //it will look like this:
   singleProduct.qtn += 1
  } else {
   productArray.push(product);
 }
    
}

您可以将 add(product) 更改为:

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

这里会搜索类似的产品(我不知道哪个是单一性标准,所以我将整个对象与整个新添加的对象进行比较),如果找到,它会更新数量,否则它会推送新产品。

和 HTML 部分:

<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