简体   繁体   English

如何计算角度 2+ 中表格列的总和?

[英]How can i calculate the sum of table column in angular 2+?

I have a table that is being filtered dynamically (Pipes) according to user selection.我有一个根据用户选择动态过滤的表(管道)。

I need to enter a summaries row at the bottom that will show the SUM of the item.total column.我需要在底部输入一个汇总行,该行将显示item.total列的 SUM。 This is the code, what is the best way to implement it?这是代码,实现它的最佳方法是什么?

  <tbody>
      <tr class="newLine" *ngFor="let item of records | filter:profile | location:selectedRegion ">
        <td scope="row">{{item.name}} </td>
        <td scope="row">{{item.profile}} </td>
        <td scope="row">{{item.location}} </td>
        <td scope="row">{{item.numOfTags}}</td>
      </tr>
      <tr>{{total numOfTags??}}</tr>
  </tbody>

I have found another way to reproduce your code with better performance Here's the code:我找到了另一种以更好的性能重现代码的方法 这是代码:

<div    *ngFor="let item of records | yourfilterChain;let last=last;let sum=ngForOf.reduce((a,b)=>a+b,0)" >
     {{item}}
     <div *ngIf="last">{{sum}} </div>
</div>

you can calculate the sum of filtered result with arrow function inside ngfor您可以使用 ngfor 中的箭头函数计算过滤结果的总和

Create a new filter pipe that calculates the sum with the current filter创建一个新的过滤器管道,用当前过滤器计算总和

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filtercount'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if(!items) return [];
    if(!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter( it => {
      return it.name.toLowerCase().includes(searchText);
    }).reduce((a, b) => a.total + b.total, 0);
   }
}

and use it like this并像这样使用它

{{records | filtercount:profile}}

It's a very simple task but most of the UI developers stuck at this point .这是一项非常简单的任务,但大多数 UI 开发人员都停留在这一点上。 So let's discuss.所以我们来讨论一下。

If we have already get the response(in JSON format)from any Web Service , ie, array of object-如果我们已经从任何 Web Service 获得响应(JSON 格式),即对象数组 -

0: {REFUND: 0, PAYMENTCANCELLED: 0, PENDING_RECHARGE: 11, OUTLIER: 0, CHANNEL: "JIO.COM", …}
1: {REFUND: 0, PAYMENTCANCELLED: 65, PENDING_RECHARGE: 0, OUTLIER: 0, CHANNEL: "JIO.COM", …}
2: {REFUND: 0, PAYMENTCANCELLED: 31, PENDING_RECHARGE: 393, OUTLIER: 0, CHANNEL: "MYJIO", …}
3: {REFUND: 0, PAYMENTCANCELLED: 319, PENDING_RECHARGE: 1, OUTLIER: 0, CHANNEL: "MYJIO", …}

let's consider the above response is loaded in like让我们考虑一下上面的响应是加载的

this.FttxRechargeReportRes = response.responsePayload;

The above thing is common and understandable to everyone.上面的事情大家都很常见,也都可以理解。 Now , to get the sum of every values of respective keys.现在,获取各个键的每个值的总和。

  getSum(){
    debugger;
    console.log(this.FttxRechargeReportRes );
    let sumArr = this.FttxRechargeReportRes .reduce((acc, cur) => {
      for (let key in cur) {
        // console.log(key, cur, acc);
        if (key !== 'RTYPE' && key !== 'CHANNEL') {  // "We did this because there was only characters in RTYPE & CHANNEL , so we could not get sum of same."
          if (acc[key]) {
            acc[key] += cur[key]
          } else {
            acc[key] = cur[key]
          }
        }
      }
      return acc;
    }, {})

    console.log(sumArr);
this.arrData=sumArr;
console.log(this.arrData);


  }

When you will print arrData , you will get the following output:-当您打印arrData 时,您将获得以下输出:-

{
REFUND: 0
PAYMENTCANCELLED: 415
PENDING_RECHARGE: 405
OUTLIER: 0
RECHARGE_SUCCESS: 15212
PAYMENTSUCCESS: 15617
PAYMENT_INITIATED: 23333
TOTAL_RECHARGE: 39365
}

You only need to print in html, that's it.你只需要在html中打印,就是这样。

I'm late but I thought it would be useful to share my fieldSum Pipe.我迟到了,但我认为分享我的fieldSum Pipe 会很有用。

When you have a list of object and you want to publish the sum of one of the fields.当您有一个对象列表并且想要发布其中一个字段的总和时。

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

/**
 * Pipe to return the sum of `attr` fields in `items`
 */
@Pipe({
  name: 'fieldSum'
})
export class FieldSumPipe implements PipeTransform {
  transform(items: any[], attr: string): number {
    // console.log('items:', items, 'attr:', attr);
    return items.reduce((a, b) => a + b[attr], 0);
  }
}

Use like:像这样使用:

{{ items | fieldSum:'qty' }}

Using as a reference this pipe implementing count, average and such is trivial.将此管道用作实现计数、平均值等的参考是微不足道的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM