I have a function that I need to call for each element that will produce 2 new outputs. For example
list = [{a : 1, b: 2}, {a:3, b: 4}]
my html would be
<div *ngFor="#item of list">{{item.c}}, {{item.d}}</div>
If you notice, I am displaying c and d. Those does not exist in the original list, but I want to call a function and calculate them so I can display them. I do not want to call the function twice. The value of d = a + b + c. This means that it depends on c
I need my template to be like this
<div *ngFor="#item of list; #newItem=calculate(item)">{{newItem.c}}, {{newItem.d}}</div>
I know that I can not use local variables for this, but can you think of another solution?
Live example:
(a) is an item price (b) is shipping costs (c) is a sales tax calculated based on (a) (d) is final price = a + b + c
I want to display:
Price: {{a}}
Taxes: {{c}}
Shipping {{b}}
Final Price: {{d}}
Prepare the data before you use it in *ngFor
list.forEach((item) => {
item.newItem = calculate(item);
})
<div *ngFor="let item of list">{{item.newItem.c}}, {{item.newItem.d}}</div>
An option would be to create a dedicated sub component to display item:
@Component({
selector: 'item',
template: `
{{item.c}}, {{item.d}}
`
})
export class ItemComponent {
@Input()
set item(item) {
this._item = this.calculate(item);
}
calculate(item) {
return ...
}
get item() {
return this._item;
}
}
and its use:
@Component({
(...)
template: `
<div *ngFor="#item of list">
<item [item]="item"></item>
</div>
`,
directives: [ ItemComponent'
])
(...)
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