Angular 如何在数组中增加一个值?

Angular 如何在数组中增加一个值?,angular,Angular,我有一个数组,它有一个值quantity。当我点击按钮时,数量应增加1个单位。目前,我对所有值都有一个增加​​将数组中的数量乘以一。如何只为一个人做 ts: html: {{item.quantity} 添加 尝试使用map而不是forEach incrementAll() { this.order.list = this.order.list.map(o => ({...o, quantity: o.quantity + 1})) } 对于增加特定项目的数量,您必须传递其各自的唯

我有一个数组,它有一个值
quantity
。当我点击按钮时,
数量应增加1个单位。目前,我对所有值都有一个增加​​将数组中的
数量
乘以一。如何只为一个人做

ts:

html:


{{item.quantity}
添加

尝试使用
map
而不是
forEach

incrementAll() {
  this.order.list = this.order.list.map(o => ({...o, quantity: o.quantity + 1}))
}
对于增加特定项目的数量,您必须传递其各自的唯一id/名称,以执行这样的条件,即按钮应位于每个项目的
ngFor
循环中:

incrementItem(id: number) {
  this.order.list = this.order.list.map(o => o.id === id ? {...o, quantity: o.quantity + 1} : o);
}

以下是传递项目模板中的供您参考

<div *ngFor="let item of testOrder2.list">
   <strong>{{ item.product }}</strong>
   <p>{{ item.quantity }}</p>
  
     <button class="btn btn-primary" 
       (click)="incrementItem(item)">Increment</button>
   </div>

stackblitz演示:

这是否回答了您的问题?你想增加哪一项的数量?
incrementItem(id: number) {
  this.order.list = this.order.list.map(o => o.id === id ? {...o, quantity: o.quantity + 1} : o);
}
<div *ngFor="let item of testOrder2.list">
   <strong>{{ item.product }}</strong>
   <p>{{ item.quantity }}</p>
  
     <button class="btn btn-primary" 
       (click)="incrementItem(item)">Increment</button>
   </div>

  incrementItem(item) {
    item.quantity++;  
  }