angular 2 how to sum column ngFor

2020-06-06 05:54发布

问题:

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

<tr *ngFor="let item of items">
    <td>{{item.num1 }}</td>
    <td>{{item.num2}}</td>
    <td>{{item.num3}}</td>
    <td>{{item.num4}}</td>
    <td>{{item.num5}}</td>
</tr>

and I need to sum all that columns below like:

<tr *ngFor="let item of items">
     <td>{{item.num1 }}</td>
     <td>{{item.num2}}</td>
     <td>{{item.num3}}</td>
     <td>{{item.num4}}</td>
     <td>{{item.num5}}</td>
</tr>
<tr>
     <td>SUM1</td>
     <td>SUM2</td>
     <td>SUM3</td>
     <td>SUM4</td>
     <td>SUM5</td>
</tr>

回答1:

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


回答2:

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


标签: angular