Search code examples
angularangular-materialmat-table

Adding Colspan to mat-table header


I want to add a colspan to a mat-table mat-header.

Current Link: https://stackblitz.com/edit/angular-bklajw-mwqqvl?file=app/table-basic-example.html

I couldn't find any other example where one mat-header-cell is used with multiple mat-cell

Desired output: enter image description here


Solution

  • you don't have to use the same array for the columns and the header columns. Use two different arrays :)

    displayedHeaderColumns: string[] = ['name', 'weight'];
    displayedColumns: string[] = ['name', 'weight', 'symbol'];
    

    Now in your template you can use displayedHeaderColumns for the headerColumns

    <ng-container matColumnDef="weight">
      <th mat-header-cell colspan="2" *matHeaderCellDef>Properties</th>
      <td mat-cell *matCellDef="let element">{{element.weight}}</td>
    </ng-container>
    
    <ng-container matColumnDef="symbol">
      <td mat-cell *matCellDef="let element">{{element.symbol}}</td>
    </ng-container>
    
    <tr mat-header-row *matHeaderRowDef="displayedHeaderColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    

    Notice the colspan attribute on the weight column.

    Here you can see the running different header columns for a matTable example.