Alternate row colours angular material table

Ben Clarke picture Ben Clarke · Nov 1, 2017 · Viewed 51.6k times · Source

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?

Answer

mohit uprim picture mohit uprim · Nov 1, 2017

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