Search code examples
javascriptangularjstypescriptngfor

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>

Solution

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