Search code examples
cssangularangular-materialmat-table

Alternate color with Angular Material mat-table with parent child rows


I have an Angular Material mat-table which I used CSS styling for alternate row colors. Here is the CSS styling:

.mat-row:nth-child(even){
    background-color: #e4f0ec;
}

.mat-row:nth-child(odd){
    background-color:#ffffff;
}

This works when my mat-table does not have defined child rows. When I added another ng-container which is specified with "expandedDetail", this does not work anymore. All the rows is white but the expanded child rows are colored.

I followed the example from material.angular.io

I see other example for row styling but they use tr tags. In the example and my code, I used an ng-container, th and td tags for each column.

Any help is appreciated.

I added the project to stackblitz

https://stackblitz.com/edit/angular-4bcxtv

Here is the HTML code I used

<table mat-table
       [dataSource]="dataSource" multiTemplateDataRows
       class="mat-elevation-z8">
  <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
    <th mat-header-cell *matHeaderCellDef> {{column}} </th>
    <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
  </ng-container>

  <!-- Expanded Content Column - The detail row is made up of this one column that spans across all columns -->
  <ng-container matColumnDef="expandedDetail">
    <td mat-cell *matCellDef="let element" [attr.colspan]="columnsToDisplay.length">
      <div class="example-element-detail"
           [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
        <div class="example-element-diagram">
          <div class="example-element-position"> {{element.position}} </div>
          <div class="example-element-symbol"> {{element.symbol}} </div>
          <div class="example-element-name"> {{element.name}} </div>
          <div class="example-element-weight"> {{element.weight}} </div>
        </div>
        <div class="example-element-description">
          {{element.description}}
          <span class="example-element-description-attribution"> -- Wikipedia </span>
        </div>
      </div>
    </td>
  </ng-container>

  <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>

Solution

  • dang it - this took me too long to find out and the worse.. I don't know excatly why it's working..

    .mat-row:nth-child(2n+1){
      background-color: #e4f0ec;
    }
    .mat-row:not(:nth-child(4n+1)){
      background-color:#ffffff;
    }
    

    I hope I could help you :)