2

I am using angular-material Mat-Table to display list of records in grid format. My requirement is to group and expand rows based on ID column value in the grid.

I am fetching data from API and assigning it to mDataSource . To achieve the group and expand behavior, I assigned mDataSource to another MatTableDataSource. So that I can maintain original records in one datasource and grouped data in another datasource. But I am not sure on how to achieve this behavior in code and html.

studentcomponent.ts

public mDataSource: MatTableDataSource<StudentClass>;

this._studentService.getStudentClass(requestStudent)
            .subscribe(data => {

                this.responseStudentClasses = data;

                let gridList;

                gridList = this.responseStudentClasses
                .StudentClass
                .map(item => new StudentClass(item));

                this.mDataSource = new MatTableDataSource(gridList);
            },
            exc => {
                this.ErrorMessage = this.ErrorMessage.setError(exc.message, null);
        });

mDataSource data will look lke this.

mDataSource = 
  {Id:1, name: 'ABC', weight: 10 },
  {Id:1, name: 'ABC', weight: 14 },
  {Id:1, name: 'ABC', weight: 16 },
  {Id:2, name: 'DEF', weight: 23 },
  {Id:2, name: 'DEF', weight: 22 },
  {Id:4, name: 'GHI', weight: 44 },
  {Id:4, name: 'GHI', weight: 41 },

My Html:

<mat-table [dataSource]="mDataSource" multiTemplateDataRows matSort>

    <ng-container matColumnDef="Id">
        <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
        <mat-cell *matCellDef="let element">{{element.ID}}</mat-cell>
    </ng-container>

    <ng-container matColumnDef="name">
        <mat-header-cell *matHeaderCellDef mat-sort-header>Name</mat-header-cell>
        <mat-cell *matCellDef="let element">{{element.name}}</mat-cell>
    </ng-container>

    <ng-container matColumnDef="weight">
        <mat-header-cell *matHeaderCellDef mat-sort-header>Weight</mat-header-cell>
        <mat-cell *matCellDef="let element">{{element.weight}}</mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="mGridDisplayCols"></mat-header-row>

    <mat-row *matRowDef="let row; columns: mGridDisplayCols;"
             (mouseover)="row.gridHovered = true"
             (mouseout)="row.gridHovered = false">
    </mat-row>

</mat-table>

My Grid will initiallay looks like this.

  ID   Name  Weight
  1     ABC   40
  2     DEF   45
  3     GHI   85

When I click on first row, it should expand and display rows like: (i.e., 10+14+16 =40)

 ID   Name  Weight
  1     ABC   40
  1     ABC   10
  1     ABC   14
  1     ABC   16
  2     DEF   45
  3     GHI   85

I would be very grateful, if someone help me to group and expand rows.