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?
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; }
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With