Adding values within NGFOR

1

I would like some help. I am generating a table within a ngFor , but I need to show in the footer of the same the sum of a certain field:

<div *ngFor="let pista of prize.pistas">
    <div>
        <h2>{{ pista.numero_pista }}</h2>
    </div>
    <table>
        <thead>
            <th>
                <h5>Prueba</h5></th>
            <th>
                <h5>Inscritos</h5></th>
        </thead>
        <tbody>
            <tr *ngFor="let p of pista.pistas;">
                <td>
                    <strong>
                                    {{ p.prueba }}
                                </strong> {{ p.nombre }}
                    <strong *ngIf="p.categoria != null">
                                    {{ p.categoria }}
                                </strong>
                </td>
                <td>{{ p.cantidad }}</td>
            </tr>
        </tbody>
    </table>
</div>

How can I do a sum within the cycle of ngFor style " var x += p.cantidad " and show it at the end of it?

    
asked by Alan Luna 31.10.2018 в 23:48
source

2 answers

2

I'm just going to supplement a bit with respect to Enrique's comment.

What is ngFor in Angular?

ngFor is a structural directive, which means that it changes the structure of the DOM. The point is to repeat a given HTML template once for each value in an array, each time you pass the value of the array as context for the interpolation or string link.

That said, the most you could do within a ngFor is to perform basic calculations (*, /, -, -) within the same row, but not as you pretend (if I understood your question correctly) ), which is to calculate the total sum of a column.

To do this, you must do it from your client of the typescript component in which you need to perform the respective calculations. I'm going to show you a brief example of x people who have bought y product for a certain amount, showing in the same row the total balance of the sale and outside of ngFor we make the sum of what they owe us z customers:

HTML example

<h4>NgFor</h4>
<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Nombre</th>
      <th>Apellido</th>
      <th>Producto</th>
      <th>Costo(Und)</th>
      <th>Cantidad</th>
      <th>Saldo</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let persona of personas, index as id">
      <td>{{ id+1 }}</td>
      <td>{{ persona.nombre_persona }}</td>
      <td>{{ persona.apellido_persona }}</td>
      <td>{{ persona.nombre_producto}}</td>
      <td>{{ persona.costo_producto | currency}}</td>
      <td>{{ persona.cantidad_producto}}</td>
      <td>{{ persona.costo_producto * persona.cantidad_producto | currency}}</td>
    </tr>
    <hr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>Total:</td>
      <td>{{ total | currency }}</td>
    </tr>
  </tbody>

Example Typescript

export class AppComponent  
{
  name = 'Angular';
  total:number;

  ngOnInit() 
  {
    //Calculamos el TOTAL 
    this.total = this.personas.reduce((
      acc,
      obj,
    ) => acc + (obj.costo_producto * obj.cantidad_producto),
    0);
    console.log("Total: ", this.total)
  }
  personas: any[] = [
    {
      'nombre_persona': 'Felipe',
      'apellido_persona':'Fernandes',
      'nombre_producto':'Computador',
      'cantidad_producto':'5',
      'costo_producto':'25000',
    },
    {
      'nombre_persona': 'Juan',
      'apellido_persona':'Suarez',
      'nombre_producto':'Equipo de Sonido',
      'cantidad_producto':'1',
      'costo_producto':'35000',
    },
    {
      'nombre_persona': 'Raul',
      'apellido_persona':'Aveiro',
      'nombre_producto':'Celular',
      'cantidad_producto':'2',
      'costo_producto':'150000',
    },
    {
      'nombre_persona': 'Humberto',
      'apellido_persona':'Castilla',
      'nombre_producto':'Toner de Impresora',
      'cantidad_producto':'15',
      'costo_producto':'12000',
    },
  ];
}

This was just an example with the multiplication operator between two objects in the matrix, you could use multiple objects and different operators to find some result.

If it's difficult to see from here, I've done a stackblitz online so you can see the operation. If you have any questions, do not hesitate to ask.

    
answered by 01.11.2018 / 15:08
source
0

ngFor is not designed for calculations, it is correct to calculate it in the component

ngOnInit(){
const sum = pista.pistas.reduce((actual, anterior) => return actual + anterior);

}

then in the template you simply show the value where you want using {{sum}}

    
answered by 01.11.2018 в 13:07