0

I'm sure this is a simple solution but really couldn't find anything online or I kept getting sent down the wrong rabbit holes...

I just want to do a simple loop and add the items to a variable for display purpose only..

<div *ngFor="let item of items">
   <div> {{ item.cost }} </div>
<div>

then outside the loop initialize a variable and within the loop and increment it

set totalCost=0
<div *ngFor="let item of items">
   <div> {{ item.cost }} </div>
   set totalCost = totalCost + item.cost
<div>

so I tried ngInit and various flavors to no avail. such as How do I get the total sum in ng-init and ng-repeat - angularjs

3
  • Why not initialize this variable in component? Commented Feb 27, 2019 at 14:03
  • You can do the calculations/assignment in component. Not in the HTML Commented Feb 27, 2019 at 14:03
  • If you want to do it in the view can do <div (click)="totalcost = totalcost + item.cost"> No need to set it to 0 first. Commented Feb 27, 2019 at 14:07

2 Answers 2

1

Do it in the component, NOT the view.

A one-liner:

totalCost = items.reduce((result, item) => result + item.cost, 0);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice: simple test [1,2,3,4].reduce((result, item) => result + item, 0); => 10 :)
0

You shouldn't do this in your HTML file, but rather do something like following

<div *ngFor="let item of items">
   <div> {{ item.cost }} </div>
<div>
   <div> {{getTotalCost()}} </div>
and in the .ts file of your component write the function

getTotalCost(){
// assuming you have a list of objects
let total = 0;
this.items.foreach(item=>{
total+= item.cost;
});
return total;
}

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.