* ng For a local variable for each element

I have a function that I need to call for each element that will produce 2 new outputs. for instance

list = [{a : 1, b: 2}, {a:3, b: 4}] 

my html will be

 <div *ngFor="#item of list">{{item.c}}, {{item.d}}</div> 

If you notice, I show c and d. They do not exist in the original list, but I want to call a function and evaluate them so that I can display them. I do not want to call this function twice. The value of d = a + b + c. This means that it depends on c

I need my template to be like that

 <div *ngFor="#item of list; #newItem=calculate(item)">{{newItem.c}}, {{newItem.d}}</div> 

I know that I cannot use local variables for this, but can you think of another solution?

Real-time example:

(a) - the price of the goods (b) the cost of delivery (c) is the sales tax calculated on the basis of (a) (d) the final price = a + b + c

I want to show:

 Price: {{a}} Taxes: {{c}} Shipping {{b}} Final Price: {{d}} 
+6
source share
2 answers

Prepare the data before using it in *ngFor

 list.forEach((item) => { item.newItem = calculate(item); }) 
 <div *ngFor="let item of list">{{item.newItem.c}}, {{item.newItem.d}}</div> 
+2
source

The parameter should consist in creating a selected auxiliary component for displaying the element:

 @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' ]) (...) 
0
source

All Articles