Alternate row colours angular material table

HtmlCssAngularAngular Material2

Html Problem Overview


I am wondering how I target the even/odd rows inside a Angular Material Table so that I can set the even/odd rows a different background colour.

I setup my ClaimFileHistoryDataSource class:

claimClientInformation: ClaimFileHistory[];
dataSource : ClaimFileHistoryDataSource;
displayedColumns = ['TypeImg', 'Description', 'Agent'];


export class ClaimFileHistoryDataSource extends DataSource<ClaimFileHistory> {
  
    constructor(private _claimFileHistory: ClaimFileHistory[]) {
      super();
    }
  
    connect(): Observable<ClaimFileHistory[]> {
      return Observable.of(this._claimFileHistory);
    }

    disconnect() {}
}

On NgInit I make a call to my service to go and get the data I need and populate the DataSource:

this._claimFileHistoryService.getClaimFileHistoryById().subscribe(response => {
  this.claimClientInformation = response;       
  this.dataSource = new ClaimFileHistoryDataSource(this.claimClientInformation);
});

This is fine and the Data is coming back as it should.

In the HTML the Mat-Table looks like this:

    <mat-table #table [dataSource]="dataSource">

      <ng-container matColumnDef="TypeImg">
        <mat-cell *matCellDef="let row"><img [src]='row.TypeImg' height="40px"></mat-cell>
      </ng-container>

      <ng-container matColumnDef="Description">
        <mat-cell *matCellDef="let row">
          <div>
            <span class="d-block">{{row.Description}}</span>
            <span class="d-block">{{row.Date}}</span>
          </div>

        </mat-cell>
      </ng-container>

      <ng-container matColumnDef="Agent">
        <mat-cell *matCellDef="let row"> {{row.Agent}} </mat-cell>
      </ng-container>

      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>

Again I was wondering how do I go about getting the Odd/Even rows of the table and setting them a different row background colour?

Html Solutions


Solution 1 - Html

Use Following CSS in your .css or .scss file to set the different style for even/odd row:

.mat-row:nth-child(even){
    background-color: red;
}
        
.mat-row:nth-child(odd){
    background-color: black;
}

Solution 2 - Html

Updating this answer with a newer approach to future developers who may come to this question.

Material Angular now offers some variables to row indexes.

<mat-row *matRowDef="
              let row;
              let even = even; 
              columns: displayedColumns;" 
		 [ngClass]="{gray: even}"></mat-row>

In you CSS file: .gray { background-color: #f5f5f5 }

There are other properties like: index, count, first, last, even and odd.

You can find out more on Angular Docs, more specifically on section "Table showing each row context properties"

Solution 3 - Html

You can apply colors to rows based on condition as well.

For an instance if the cell value is equal to 100,then change the color of the row to red.

     <tr class="matheader-row" mat-row *matRowDef="let row; columns: displayColumns; 
      let i = index; let even = even;" [class.rowStyle]="row['myColumn']=='100'"
                [ngClass]="{rowcolor: even}">
        </tr>

css

.rowStyle{
background-color:red;
font-weight: bold;
}

Above scenario will work if your columns have myColumn as one of the columns. Also using even property you can apply the required color styling [ngClass]="{rowcolor: even}

Solution 4 - Html

if you use themes a transparent css looks nice:

.mat-row:nth-child(odd){
  background: rgba(0,0,0,0.025);
}

Solution 5 - Html

Unfortunatly none of the above answers worked for me (i'm using multiTemplateDataRows), but after tweaking Gustavo Lopez answer i got it to work as below:

<tr *matRowDef="
          let row;
          let index = dataIndex;
          columns: displayedColumns;" 
     [ngClass]="{alternate: index % 2 == 0 }"></tr

And the css is as previous answer:

.alternate { background-color: #f5f5f5 }

It seems like no of the properties like odd,even or index work when you have multiTemplateDataRows but fortunately they've solved the index property with dataIndex (https://github.com/angular/components/issues/12793#issuecomment-415356860). Hopefully this will help others that have expandable rows.

Solution 6 - Html

The answers of @mohit uprim and @Gustavo Lopes did work for me for a Material Angular datatable. But whenever I hover above the line, the row gets its initial default colour (white) and restores the new CSS colour on mouse-out event. So, adding "important" flag should fix it :

.some-class-name {
    background-color: blue !important; 
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen ClarkeView Question on Stackoverflow
Solution 1 - Htmlmohit uprimView Answer on Stackoverflow
Solution 2 - HtmlGustavo LopesView Answer on Stackoverflow
Solution 3 - HtmlHameed SyedView Answer on Stackoverflow
Solution 4 - HtmlTimelotView Answer on Stackoverflow
Solution 5 - HtmlTommiView Answer on Stackoverflow
Solution 6 - HtmlOmarView Answer on Stackoverflow