显示对象数组中“实时”数量之和的最佳方法

时间:2019-04-17 15:30:51

标签: angular typescript

下面是我拥有的数组。我正在构建一个离子/角度应用程序,并希望在屏幕上显示“总计”,这将是下面对象数组中“数量”的总和。

此数组可以添加对象,数量也可以增加/减少...但是我希望该总数反映发生的更改。最好的方法是什么?

enter image description here

3 个答案:

答案 0 :(得分:1)

这一行应该做到

let sum = LotsForCheckIn.map(lot => lot.Quantity).reduce((prev, curr) => prev + curr, 0);

更新:

我要在这里假设您在某个地方的组件中拥有一个LotsForCheckIn作为类属性。

组件html:

<div>
Total {{sum()}}
</div>

组件ts:

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  LotsForCheckIn = [];

  sum(){
    this.LotsForCheckIn
      .map(lot => lot.Quantity)
      .reduce((prev, curr) => prev + curr, 0);
  }
}

现在,列表的任何更改都将反映在用户界面中,而无需任何其他代码。

答案 1 :(得分:0)

您可以这样做:

let sum = 0;
LotsForCheckIn.foreach( (found:any) => {
  if (found.Quantity != null){
    sum += found.Quantity;
  }
});

答案 2 :(得分:0)

在组件类中编写以下函数。

//  i am assuming below are properties of the component class
totalQuantity:number;
LotsForCheckIn:any[];

calculateTotalQuantity(){
this.totalQuantity = 0;
   this.LotsForCheckIn.forEach((lot:any)=>{
      this.totalQuantity += lot.Quantity;
  });
}

向组件类模板添加类似于以下内容的数据绑定totalQuantity。

<p>Total Quantity - {{totalQuantity}},</p>

LotsForCheckIn 发生更改时,调用 calculateTotalQuantity()。我已将任何商品分配给lot和LotsForCheckIn。最好定义接口并将其指定为数据类型。