【问题标题】:Show sum of data outs in ngFor after it's filtered by pipe (Angular2)在通过管道(Angular2)过滤后显示ngFor中的数据总和
【发布时间】:2017-05-04 05:59:35
【问题描述】:

我希望在应用管道过滤器后显示我的 json 对象中的金额值的总和,该管道过滤器按对象的名称值过滤它们。到目前为止,我可以通过它们的 .json 对象的名称值过滤数字,但我无法在管道中使用 .reduce() 方法找到并显示总和。

如何显示我的管道按名称值过滤的金额总计?

最终,我希望用户搜索一个城市并查看每个对象的数值的总和,该数值可通过相同的城市名称识别。
(我正在构建本教程https://www.youtube.com/watch?v=sVTNaYBVP88&list=PL4cUxeGkcC9jqhk5RvBiEwHMKSUXPyng0&index=22

json 示例

[
{
"name": "Bacon",
"belt": "purple",
"amount": 23
},
{
"name": "Alex",
"belt": "purple",
"amount": 24
},
{
"name": "Alex",
"belt": "black",
"amount": 232
}
]

组件 HTML

<li *ngFor="let ninja of ninjas | filter:term | sum" >
<p>{{ninja.amount}}</p>
</li>

总管

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sum'
})
export class SumPipe implements PipeTransform {

  transform(ninjas: any, term: any): any {

  return ninjas.reduce(function(a,b){return a + b});
  }
}

【问题讨论】:

    标签: json angular angular2-pipe


    【解决方案1】:

    我不认为你可以。过滤 xour 组件或服务中的数据,并将过滤后的 redult 分配给一个字段,并将 ngFor 绑定到该字段。从过滤后的数据中计算总和并将其分配给一个字段并将视图绑定到该字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 2017-05-15
      • 2016-09-08
      • 2017-07-02
      相关资源
      最近更新 更多