Angular 2: Calculate sum of an element in ngFor

前端 未结 2 645
走了就别回头了
走了就别回头了 2021-01-15 05:36

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

HTML

 
相关标签:
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.

    0 讨论(0)
  • 2021-01-15 06:26

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

    0 讨论(0)
提交回复
热议问题