How to add object property in Array to *ngFor

Asked

Viewed 979 times

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>

2 answers

1


I suggest you process the total in the controller, it could be 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 to sum. The total you can save into a scope variable and display where you need to.

1

As you want the sum of all elements, you should not put yourself inside ngFor which is where you present something for each element. If you don’t 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 believe you might want the value multiplied by the amount, which is:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.