Angular Material mat-table Row Grouping from property

Viewed 30

I want to display the data in one row with the same ID. But now I have this:

data:

{ "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": "22/09/2022 06:00", "valore": "13,8" }, { "id": "700", "desc": "Tempo", "richiesta": "20220088", "dataElab": "21/09/2022 06:00", "valore": "12,9" }, { "id": "700", "desc": "Tempo", "richiesta": "20220089", "dataElab": "20/09/2022 06:00", "valore": "12,8" }

This is the HTML code:

  
<table mat-table [dataSource]="data" class="mat-elevation-z8" width="100%">
  
  
  <!-- ID Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td mat-cell *matCellDef="let element"> {{element.id}} </td>
  </ng-container>
  
  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> 
    {{element.desc}} </td>
  </ng-container>

  <ng-container *ngFor="let columns of displayedDateColumns" [matColumnDef]="columns">
    <th mat-header-cell *matHeaderCellDef> {{columns}} </th>
    <td mat-cell *matCellDef="let element"> 
    <ng-container *ngIf="element.dataElab == columns">
    {{element.valore}} 
    </ng-container>
    </td>
  </ng-container>
  
 
  <tr mat-header-row *matHeaderRowDef= displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

current view

How to do this:

desired view

Thanks

1 Answers

You need Array.reduce() to iterate each element in the array, append key-value pair with dataElab as key and valore as value to the element and add the element into a new array.

this.data = this.data.reduce((acc: any[], cur: any) => {
  let index = acc.findIndex((x) => x.id == cur.id);
  if (index == -1) {
    cur[cur.dataElab] = cur.valore;
    acc.push(cur);
  } else {
    acc[index][cur.dataElab] = cur.valore;
  }

  return acc;
}, []);

Date columns

<ng-container
  *ngFor="let columns of displayedDateColumns"
  [matColumnDef]="columns"
>
  <th mat-header-cell *matHeaderCellDef>{{ columns }}</th>
  <td mat-cell *matCellDef="let element">
    {{ element[columns] }}
  </td>
</ng-container>

Demo @ StackBlitz

Related