【问题标题】:How can i calculate the sum of table column in angular 2+?如何计算角度 2+ 中表格列的总和?
【发布时间】:2019-03-26 05:59:04
【问题描述】:

我有一个根据用户选择动态过滤的表(管道)。

我需要在底部输入一个摘要行,该行将显示item.total 列的总和。 这是代码,最好的实现方式是什么?

  <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>

【问题讨论】:

    标签: javascript angularjs typescript ngfor


    【解决方案1】:

    我找到了另一种以更好的性能重现您的代码的方法这是代码:

    <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>
    

    您可以在ngfor中使用箭头函数计算过滤结果的总和

    【讨论】:

      【解决方案2】:

      创建一个新的过滤器管道,计算与当前过滤器的总和

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

      并像这样使用它

      {{records | filtercount:profile}}
      

      【讨论】:

      • 谢谢,但是如果我还有其他管道怎么办?我可以将它完全分离并使其作为最后一个管道运行吗?
      • 你能说清楚并命名你的其他过滤器吗?你想在哪里使用这些过滤器?这些过滤器有什么作用?
      • 我还有 2 个其他管道“| filter:profile | location:selectedRegion”,它们按字符串过滤行,在它们进行过滤后,我需要过滤总列的总和。 (更新后的代码更清晰)
      • 哦,我看到您想使用位置和文本搜索等来过滤您的数据。您可以链接您的过滤器,最后一个过滤器将是您的新过滤器计数。只需从 filtercount 管道中删除搜索过滤器,只需计算输入数组的总数,在先前过滤器的帮助下,filtercount 管道的输入数组将是过滤后的数据,您需要做的就是计算其计数
      • 太棒了!那行得通!刚刚创建了新过滤器并将其放在过滤器链的最后:)
      【解决方案3】:

      这是一项非常简单的任务,但大多数 UI 开发人员都停留在这一点上。那么我们来讨论一下吧。

      如果我们已经从任何 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", …}
      

      让我们考虑一下上面的响应是像这样加载的

      this.FttxRechargeReportRes = response.responsePayload;
      

      以上的事情大家都很普遍,也可以理解。现在,获取各个键的每个值的总和。

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

      当你打印 arrData 时,你会得到以下输出:-

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

      你只需要用html打印就可以了。

      【讨论】:

        【解决方案4】:

        我迟到了,但我认为分享我的fieldSum Pipe 会很有用。

        当您有一个对象列表并且想要发布其中一个字段的总和时。

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

        像这样使用:

        {{ items | fieldSum:'qty' }}
        

        将此管道用作实现计数、平均值等的参考是微不足道的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-07
          • 2017-11-10
          • 2019-01-18
          • 1970-01-01
          • 2014-06-23
          • 2021-03-24
          • 2023-03-25
          • 2020-01-02
          相关资源
          最近更新 更多