Select rows, add amounts and display the total in angular

Hello.

I need that when selecting several rows of a table in angular, it adds the amounts and shows them to me in the html.

I have managed to add the amounts after selecting the rows and pressing a button.

I need it to add the amounts as I select the rows (not when I press a button) and show it to me in a div in the html.

Can somebody help me?

This is what I have so far.

My html:

<tbody>
    <tr *ngFor="let item of articulos; index as i" (click)="sumarCantidad(i)">
		<td>{{item.articulo}}</td>
		<td>{{item.cantidad}}</td>
		<td>{{item.recogida}}</td>
    </tr>
    <br>
    <button (click)="total()">CANTIDAD</button>
</tbody>

My ts:

export class EntryOrderLinesComponent implements OnInit {
  selected: any[];
  articulos = [];

  constructor(private datosService: DatosService, private fb: FormBuilder) {
    this.articulos = [
      {
        articulo: '385/65X22.5 HANKOOK AH51 160K (3003836)',
        cantidad: '94',
        recogida: '0',
      },
      {
        articulo: '385/65X22.5 HANKOOK TH31 164K (3003309)',
        cantidad: '60',
        recogida: '0',
      },
    ];

    this.selected = [];
  }

  sumarCantidad(i: number) {
    const valor = this.articulos[i].cantidad;
    this.articulos[i].cantidad = +valor;
    this.selected.push(this.articulos[i]);
  }

  total() {
    const total = this.selected.map((valor) => valor.cantidad);
    console.log(
      total.reduce((acumulado, valorActual) => acumulado + valorActual, 0)
    );
  }

}

Thank you

Hi @mbeltracortes,

Just for future reference, you can select your code in the text editor and click on the </> button to format it. This makes it easier for people to read your code and give you assistance.

I have done it for you this time. :slight_smile:

Thanks.

2 Likes