Search code examples
angularangular-material2mat-table

How to fix this material table with expandable row example when using mat-* elements


I'm trying to apply the same principles to get an expandable row for my tables in the "Table with expandable rows" example.

I have styled my version of the tables similarly but cannot get the expanded portion of the tables correctly rendered. The expanded details doesn't expand the corresponding row, it just renders on top of the table overlapping. The only difference with my version is that I'm using the custom mat-* elements to create the tables.

using native elements

<table mat-table ...>
  ...
  <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let element; columns: columnsToDisplay;"
      class="example-element-row"
      [class.example-expanded-row]="expandedElement === element"
      (click)="expandedElement = expandedElement === element ? null : element">
  </tr>
  <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr>
</table>

enter image description here

using mat-* elements

<mat-table ...>
  ...
  <mat-header-row *matHeaderRowDef="columnsToDisplay"></mat-header-row>
  <mat-row *matRowDef="let element; columns: columnsToDisplay;"
      class="example-element-row"
      [class.example-expanded-row]="expandedElement === element"
      (click)="expandedElement = expandedElement === element ? null : element">
  </mat-row>
  <mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></mat-row>
</mat-table>

enter image description here

From my understanding, it's the styling of the mat-* elements that's causing issues. I definitely had to make some tweaks to the style to fix some issues, but I don't know what else to do to fix the example completely.

mat-table {
  width: 100%;
}

mat-row.example-detail-row {
  height: 0;
  min-height: initial; /* override mat-row styling */
}

mat-row.example-element-row:not(.example-expanded-row):hover {
  background: whitesmoke;
}

mat-row.example-element-row:not(.example-expanded-row):active {
  background: #efefef;
}

.example-element-row, /* override mat-row styling */
.example-element-row mat-cell {
  border-bottom-width: 0;
}

How can I fix this?

stackblitz


Solution

  • It turns out that the problem is that since the <mat-row> elements uses flex, I needed to use flex-basis to set the initial height of the detail row, rather than using height. That way the height could be adjusted when its content changes.

    mat-row.example-detail-row {
      /* height: 0; */ /* no */
      flex-basis: 0; /* yes */
      min-height: initial; /* override mat-row styling */
    }
    

    updated stackblitz