Somma di una colonna in una PrimeNG p-table

Mattepuffo's logo
Somma di una colonna in una PrimeNG p-table

Somma di una colonna in una PrimeNG p-table

Quello che vediamo in questo articolo è come sommare una colonna in una p-table di PrimeNG.

L'esempio è ripreso da un caso reale, quindi vi riporto il codice completo.

Partiamo dalla interface:

export interface Movimento {
    mov_id?: number;
    mov_valore?: number;
    mov_tipo?: string;
    mov_causale?: string;
    mov_conto?: string;
    mov_data?: string | Date;
    mov_note?: string;
    mov_data_aggiunta: string;
}

Quello che andremo a sommare è il campo mov_valore.

Come secondo step vediamo il service da cui riprendiamo i dati:

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {Movimento} from '../_interfaces/movimento';

@Injectable({
    providedIn: 'root'
})

export class MovimentoService {

    private baseUrl: string = 'https://www.sito.it/api;

    constructor(private http: HttpClient) {
    }

    getAll(anno: string): Observable<{ data: Movimento[] }> {
        let url = `${this.baseUrl}/movimenti/get.php?anno=${anno}`;

        return this.http.get(url).pipe(
            map((res: { data: Movimento[] }) => res)
        );
    }
}

A questo punto vediamo il component:

import {Component, OnInit} from '@angular/core';
import {BreadcrumbService} from '../../app.breadcrumb.service';
import {ActivatedRoute} from '@angular/router';
import {MovimentoService} from '../../_services/movimento.service';
import {Movimento} from '../../_interfaces/movimento';

@Component({
    selector: 'app-movimenti',
    templateUrl: './movimenti.component.html',
    styleUrls: ['./movimenti.component.scss']
})

export class MovimentiComponent implements OnInit {

    titolo: string;
    anno: number;
    movimenti: Movimento[];
    sumValore: number;

    constructor(
        private breadcrumbService: BreadcrumbService,
        private route: ActivatedRoute,
        private movSrv: MovimentoService
    ) {
        this.breadcrumbService.setItems([
            {label: 'Movimenti', routerLink: ['']}
        ]);

        const dd = new Date();
        this.anno = dd.getFullYear();
    }

    ngOnInit(): void {
        this.anno = Number(this.route.snapshot.paramMap.get('anno')) ?? this.anno;
        this.titolo = 'Movimenti anno ' + this.anno;

        this.minAnno = 0;
        this.sumValore = 0;

        this.getData();
    }

    getData(): void {
        this.movSrv.getAll(this.anno.toString()).subscribe((res) => {
            this.movimenti = [...res.data];

            const sum: number = this.movimenti.map(a => a.mov_valore).reduce((a, b) => {
                return Number(a) + Number(b);
            });
            
            this.sumValore = Number(sum.toFixed(2));
        });
    }

}

Qui vediamo come eseguire la somma.

In pratica usiamo la funzione map sull'array di oggetti che prendiamo da remoto.

Infinee nella nostra tabella (vi mostro solo footer):

<p-table #dt [value]="movimenti">

    <ng-template pTemplate="header">
        <tr>
            
        </tr>
    </ng-template>

    <ng-template pTemplate="body" let-item>
        <tr class="p-selectable-row">
            
        </tr>
    </ng-template>

    <ng-template pTemplate="summary">
        Totale: {{sumValore}}
    </ng-template>

</p-table>

Come vedete usiamo il pTemplate summary per visualizzare l'informazione calcolata nel component.

Enjoy!


Condividi

Commentami!