apply colspan on specific column on a dynamic table using mat-table

Viewed 114

I have mat-table in which columns get created dynamically I want to add a expand column functionality using [attr.colspan] if a click event is detected on a column header the attr gets applied on that specific column

inserting it in the HTML template applies the change to the first column

 <ng-container
matColumnDef="{{ column }}"
*ngFor="let column of displayedColumns">
<th mat-header-cell *matHeaderCellDef (click)="headerEvent(column)">{{ column }}</th>
<td mat-cell *matCellDef="let element"
[attr.colspan]="1"
>{{ element[column] }}</td>
</ng-container>

How can I apply the [attr.colspan] dynamically ?

stack blitz

1 Answers

Yes, you can use any expresion, e.g.

<th mat-header-cell *matHeaderCellDef (click)="headerEvent(column)">
  {{ column }}
</th>
<ng-container mat-cell *matCellDef="let element">
  <td
    *ngIf="!element.colspan || column != 'name'"
    [attr.colspan]="column == 'position'?element.colspan:null"
  >
    {{ element[column] }}
  </td>
</ng-container>

And you have data some like

 [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He',colspan:2}
 ]

See your forked stackblitz

See that you "remove" the next td when you make a colspan

Related