How to add property of Array objects in a * ngFor

1

I have an array passed to a * ngFor, how do I sum the values of a property, vlr, for example.

order=[
  {"qtd": Number(1),"vlr":Number(3.50)},
  {"qtd": Number(6),"vlr":Number(4.00)},
  {"qtd": Number(2),"vlr":Number(1.20)}
];
<div *ngFor="let e of order">
  <div *ngIf="e.qtd != 0">
    <ion-grid>
      <ion-row>        
        <ion-col width-33 text-center>
              <span>{{e.qtd}}</span>
        </ion-col>
        <ion-col width-33 text-center>
          <span>{{e.vlr}}</span>
        </ion-col>
      </ion-row>
    </ion-grid>
  </div>
</div>
    
asked by anonymous 01.05.2017 / 23:16

2 answers

1

I suggest that you process the total in the controller, it might look like this:

var order=[
  {"qtd": Number(1),"vlr":Number(3.50)},
  {"qtd": Number(6),"vlr":Number(4.00)},
  {"qtd": Number(2),"vlr":Number(1.20)}
];
var total = order.reduce( function(a, b){
        return a + b['vlr'];
    }, 0);
    
console.log(total);

I used Array # Reduce for make the sum. The total you can save in a scope variable and display where you need it.

    
02.05.2017 / 17:31
1

As you want the sum of all elements, one should not put inside the ngFor which is where you present something for each element. If you do not want to follow Lucas Costa's recommendation, you can use:

{{order.reduce((acumulado,linha) => acumulado + linha.vlr, 0)}}

For example:

<div *ngFor="let e of order">
  <div *ngIf="e.qtd != 0">
    <ion-grid>
      <ion-row>        
        <ion-col width-33 text-center>
              <span>{{e.qtd}}</span>
        </ion-col>
        <ion-col width-33 text-center>
          <span>{{e.vlr}}</span>
        </ion-col>
      </ion-row>
    </ion-grid>
  </div>
</div>
<div>Total: {{order.reduce((acumulado,linha) => acumulado + linha.vlr, 0)}}</div>

But I think you might want the value multiplied by the quantity, which stays:

{{order.reduce((acumulado,linha) => acumulado + linha.qtd * linha.vlr, 0)}}
    
02.05.2017 / 21:15