角2如何求和列ngFor [英] angular 2 how to sum column ngFor

查看:102
本文介绍了角2如何求和列ngFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解如何对表中的列求和,每个都加* ngFor(如todo-list),我想对列之一求和,我该如何在角度2中做到这一点? 所以我有这样的表:

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>

推荐答案

您必须在Angular 2 Component类中创建一个getSum(index:number):number方法,如下所示:

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

并在您的html中,将SUMX替换为:

and in your html, replace your SUMX by:

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

当然,如果需要,您当然也可以使用ngFor来创建多个td标签.

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

:根据您的小提琴获得所需的确切代码:

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

和html中的

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

:仅出于完整性考虑,您还可以使用reduce函数而不是在getSum方法中使用循环来对数组求和:

: 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如何求和列ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆