Eli
Eli

Reputation: 626

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

Upvotes: 2

Views: 13127

Answers (4)

Paolo Casciello
Paolo Casciello

Reputation: 8202

I'm late but I thought it would be useful to share my 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.

Upvotes: 0

Devashish Maurya
Devashish Maurya

Reputation: 72

It's a very simple task but most of the UI developers stuck at this point . So let's discuss.

If we have already get the response(in JSON format)from any Web Service , i.e., array of object-

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

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

Upvotes: 2

Mohammad Reza Farahani
Mohammad Reza Farahani

Reputation: 287

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

Upvotes: 2

Mohammad Reza Farahani
Mohammad Reza Farahani

Reputation: 287

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

Upvotes: 1

Related Questions