Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*ngFor local variable for each element

Tags:

angular

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}}
like image 529
Mohy Eldeen Avatar asked Mar 13 '16 08:03

Mohy Eldeen


Video Answer


2 Answers

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>
like image 154
Günter Zöchbauer Avatar answered Oct 04 '22 03:10

Günter Zöchbauer


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'
])
(...)
like image 45
Thierry Templier Avatar answered Oct 04 '22 03:10

Thierry Templier