角度2:计算ngFor中元素的总和 [英] Angular 2: Calculate sum of an element in ngFor

查看:111
本文介绍了角度2:计算ngFor中元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算ngFor以外的总数(金额之和).

I am trying to calculate the total (sum of amounts) outside the ngFor.

HTML

 <div *ngFor="let item of items">
    <input type="text" [(ngModel)]="item.price">  
    <input type="text" [(ngModel)]="item.quantity" (ngModelChange)="item.amount=item.quantity*item.price">
    <input type="text" [(ngModel)]="item.amount">    
</div>
<input type="text" [(ngModel)]="totalAmount">

刮擦

getTotal() {
    let total = 0;
    for (var i = 0; i < this.items.length; i++) {
        if (this.items[i].amount) {
            total += this.items[i].amount;
            this.totalamount = total;
        }
    }
    return total;
}

当我调用 getTotal()函数时,它将返回合计.但是,如何在文本框中调用它呢?或任何其他方法.

When I call the getTotal() function it returns total. But,how can I call that in textbox? or any other methods.

任何人都可以帮我解决这个问题.

Can any one help me how to solve this.

推荐答案

您始终可以使用单向绑定{{ }}

You can always bind to the function on your template by using the one-way bind {{ }}

在代码中,如果您想调用函数并将其直接绑定到视图,则可以这样做:

In your code if you wanted to call your function and bind it directly to your view you would do such:

<input type="text" value='{{ getTotal() }}' />

这篇关于角度2:计算ngFor中元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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