Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Material table highlight a row

I'm looking for a good way to highlight the whole a row in md-table.
Should I do directive or what?

<div class="example-container mat-elevation-z8">   <md-table #table [dataSource]="dataSource">      <!--- Note that these columns can be defined in any order.           The actual rendered columns are set as a property on the row definition" -->      <!-- ID Column -->     <ng-container cdkColumnDef="userId">       <md-header-cell *cdkHeaderCellDef> ID </md-header-cell>       <md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>     </ng-container>      <!-- Progress Column -->     <ng-container cdkColumnDef="progress">       <md-header-cell *cdkHeaderCellDef> Progress </md-header-cell>       <md-cell *cdkCellDef="let row"> {{row.progress}}% </md-cell>     </ng-container>      <!-- Name Column -->     <ng-container cdkColumnDef="userName">       <md-header-cell *cdkHeaderCellDef> Name </md-header-cell>       <md-cell *cdkCellDef="let row"> {{row.name}} </md-cell>     </ng-container>      <!-- Color Column -->     <ng-container cdkColumnDef="color">       <md-header-cell *cdkHeaderCellDef>Color</md-header-cell>       <md-cell *cdkCellDef="let row" [style.color]="row.color"> {{row.color}} </md-cell>     </ng-container>      <md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>     <md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>   </md-table> </div> 

Table from: https://material.angular.io/components/table/overview

like image 648
Taison Morris Avatar asked Jul 31 '17 13:07

Taison Morris


People also ask

What is MatColumnDef?

MatColumnDef extends CdkColumnDefDefines a set of cells available for a table column.


1 Answers

Update for Newer Material Version (md --> mat):

html:

<!-- Add the highlight class in row definiton of md-table --> <!-- Add click event to pass the selected row index -->  <mat-row *cdkRowDef="let row; columns: displayedColumns;"           [ngClass]="{'highlight': selectedRowIndex == row.id}"          (click)="highlight(row)"> </mat-row> 

Original Answer:

You can do it by using ngClass and a flag like selectedRowIndex. Whenever clicked row index is equal to selectedRowIndex, the class will be applied.

Plunker demo

html:

<!-- Add the highlight class in row definiton of md-table --> <!-- Add click event to pass the selected row index -->  <md-row *cdkRowDef="let row; columns: displayedColumns;"           [ngClass]="{'highlight': selectedRowIndex == row.id}"          (click)="highlight(row)"> </md-row> 

css:

.highlight{   background: #42A948; /* green */ } 

ts:

selectedRowIndex = -1;  highlight(row){     this.selectedRowIndex = row.id; } 
like image 183
Nehal Avatar answered Sep 21 '22 02:09

Nehal