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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With