angular 2 how to sum column ngFor

后端 未结 2 1121
野趣味
野趣味 2021-02-11 06:14

trying to understand how to sum the column from table, every is added with *ngFor ( like todo-list), i wanna sum one of column, how i can do it in angular 2 ? So i have table

相关标签:
2条回答
  • 2021-02-11 06:51
    getSum(): number {
        let sum = 0;
        for (let i = 0; i < this.items.length; i++) {
          sum += this.items[i].num1;
        }
        return sum;
      }
    
    0 讨论(0)
  • 2021-02-11 06:58

    You would have to create a getSum(index: number): number method in your Angular 2 Component class, something like this:

    getSum(index: number) : number {
      let sum = 0;
      for(let i = 0; i < this.items.length; i++) {
        sum += this.items[i][index];
      }
      return sum;
    }
    

    and in your html, replace your SUMX by:

    <td>{{ getSum(0) }} </td><td>{{ getSum(1) }}</td> ...
    

    And you could of course also use a ngFor to create the multiple td tags if needed.

    [EDIT]: to have the exact code you need based on your fiddle:

      getSum(column) : number {
        let sum = 0;
        for(let i = 0; i < this.list.length; i++) {
          sum += this.list[i][column];
        }
        return sum;
      }
    

    and in html:

    <td>{{ getSum('newInput') }}</td><td>{{ getSum('newOutput') }}</td>
    

    [EDIT 2]: just for completeness, you can also do the sum of an array using the reduce function rather than using a loop in the getSum method:

    var sum = this.items[i]['myfield'].reduce(function(x, y) { return x + y; }, 0);
    
    0 讨论(0)
提交回复
热议问题