4

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.

4 Answers 4

11

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

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

Comments

2

Your reduce function works well. However it's a bad practice to use expressions in angular bindings.

Move your logic to your component and call a method or getter.

Comments

0

Map and reduce return a new array. This is where your error comes from.

You can use a getter like this https://stackblitz.com/edit/angular-whrfxp. Template shouldn't contain calculations.

Comments

0

totals.reduce((a, b) => a += (b. itemCount), 0) works

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.