Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Sum totals with reduce function

Beginning here, I am attempting to sum a specific property for an array of objects by using the javascript reduce function within angular bindings.

Component

totals: total[] = [{itemCount:1},{itemCount:2},{itemCount:3}, {itemCount:4}];

HTML

<div>{{ totals.map(t => t.itemCount).reduce((a, b) => a + b, 0) }}</div>

With the above, I'm getting the Error: "Bindings cannot contain assignments"

stackblitz mockup

Thanks in advance

EDIT

I have marked the answer provided by @quirimmo as correct but I also wanted to address @jo_va answer.

I felt providing a method for angular inside my component is the right approach @quirimmo, however in my case, the component was JIT compiled on client request and at this time, I'm still uncertain as how to add that method dynamically during that component construction. This lead me to the Expression approach inside my HTML and knowingly avoiding @jo_va's answer of best practice.

My resolution was to pass along a service as an object to the component and place the method within that service for reference.

Thanks for the help S.O.

like image 589
jgritten Avatar asked Dec 11 '22 03:12

jgritten


1 Answers

Define a function inside your component which returns the reduced value and inside the binding call that function of the component:

const totals = [{itemCount:1},{itemCount:2},{itemCount:3}, {itemCount:4}];

console.log(totals.reduce((acc, val) => acc += val.itemCount, 0));
like image 139
quirimmo Avatar answered Dec 12 '22 17:12

quirimmo