In my application, I need to have some forms with strings of values ββthat need to be summed. I need to iterate over these lines, having inputs for them, and then build the amount that needs to be updated when editing the inputs.
Here is a simplified example: Class:
export class example { items = [ { id: 1, val: 100 }, { id: 2, val: 200 }, { id: 3, val: 400 } ]; get sum() { let sum = 0; for (let item of this.items) { sum = sum + parseFloat(item.val); } return sum; } }
View:
<div repeat.for="item of items" class="form-group"> <label>Item ${$index}</label> <input type="text" value.bind="item.val" class="form-control" style="width: 250px;"> </div> <div class="form-group"> <label>Summe</label> <input type="text" disabled value.one-way="sum" class="form-control" style="width: 250px;" /> </div>
So far, everything is working as I expect. But: this is a dirty check on sum all the time, and I'm afraid to run into performance issues in a more complex application. So I tried using the @computedFrom decorator, but none of these versions work:
@computedFrom('items') @computedFrom('items[0]', 'items[1]', 'items[3]') @computedFrom('items[0].val', 'items[1].val', 'items[3].val')
In all these cases, the sum is calculated only once, but not after editing the values. And the last 2 will not be a good solution, because I may have a change in the number of elements in my model.
Any suggestions on how I can get a computed value that changes when the fields it depends on are changed without checking dirty?