【问题标题】:Get SUM of a table column with 'for loop' in angular2在angular2中获取带有“for循环”的表列的总和
【发布时间】:2017-10-06 16:40:44
【问题描述】:

我正在尝试获取“表”列 (getShotsTotal) 的总和,“forEach”在 Ionic1 中运行良好,但在 Ionic2 中失败,任何帮助将不胜感激。我认为可能需要一个标准的“循环”,但作为一个新手,我不确定正确的方法和代码。

HTML:

<tr class="row header" *ngFor = "let par of Course; let i=index" >
<td class="col">{{i +1}}</td>
<td class="col1">{{par.Index}}</td>
<td class="col">{{par.Par}}</td>
<td class="col2">{{getPoints(par)}}</td>
<td class="col">{{getShots()}}</td>
<td class="col3" ><select [(ngModel)]="par.sel" 
(change)="onChangeScore(par.sel)"><option  *ngFor= "let s of items" >{{s}}
</option></select></td>
</tr>

<tr class="row" style="height:32px">
<td class="col">Total</td>
<td class="col"></td>
<td class="col"></td>
<td class="col"></td>
<td class="col">{{getTotalShots()}}</td>
<td class="col"></td>
</tr>

TS:

getShots(par) {
let val =  this.selectedHcp - par.Index;
if (val > 17.4) {
  return 2;
} else if (val >= -0.5) {
  return 1;
} else if (val < -0.5) {
  return 0;
}
};


getTotalShots = function () {
if (!this.Par) { return 0;
                 }
var total = 0;
angular.forEach(this.Par, function (item, index) {
total = total + (this.getShots(item) || 0);
});
return total;
}; 

【问题讨论】:

    标签: angular typescript angular2-template


    【解决方案1】:

    如果要循环存储在this.Par中的数组,可以直接使用forEach

    var total = 0;
    this.Par.forEach((item, index) => {
        total += this.getShots(item) || 0
    });
    

    【讨论】:

    • 感谢您的快速回复,但是我收到以下错误:无法读取未定义的属性 'forEach'
    • 所以属性 this.Par 是未定义的,或者它可能在另一个上下文中定义。可以显示组件代码吗?
    • 不太确定您要的是什么:export class CardPage { Par : any; }
    • 在模板中你在 Course 上使用 ngFor,你不应该用它来代替 Par 吗?然后您可以使用this.Course.forEach 进行迭代
    • 你们太棒了!! this.Course.forEach((item, index) => { total += this.getShots(item) || 0 });像梦一样工作!!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2017-02-18
    • 2018-12-27
    • 2020-11-04
    • 2015-04-18
    • 1970-01-01
    • 2019-07-12
    相关资源
    最近更新 更多