2

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">

Scripe

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

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.

2
  • Calc the sum in the model (items) instead and bind to the result. Commented Oct 3, 2016 at 9:32
  • Thanks for reply. I am adding items dynamically from UI. So, I am not able to calculate. Commented Oct 3, 2016 at 9:35

2 Answers 2

3

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() }}' />

Sign up to request clarification or add additional context in comments.

Comments

2

I think Angular need something more intrinsic to achieve this. The {{items}} above is simply an array and things are simple. If it were an observable, then you'll be subscribing to it in the template and in the class. If the observable is filtered in the ngFor, then you need to repeat the filtering in the class method.

The best that I can come up with is a pipe:

<div *ngFor="let item of items$ | async as list">
</div>
<div>{{list.reduce((acc,val) => acc + val.amount, 0)}}</div>

I can't imagine why you should want to bind the computed sum to an input field, so I just displayed the value here.

Unfortunately, it still means looping the list twice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.