Mourad Idrissi Mourad Idrissi - 1 month ago 14
CSS Question

How to highlight a selected row in *ngFor?

I couldn't find something that will help me to solve this issue in Angular2. I'd like to set a css class when I select a row. (without using jQuery)

<table class="table table-bordered table-condensed table-hover">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Website</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of companies" (click)="selectedCompany(item, $event)">
<td>{{item.name}}</td>
<td>{{item.email}}</td>
<td>{{item.website}}</td>
</tr>
</tbody>
</table>


I'm using Angular2 final release

Answer

There are plenty of solutions to do this, one of them is you can store the current company when clicked.

In the *ngFor you check if the current item is the currentCompany and you add the class highlighted or whatever class you wish if its the same company.

export class TableComponent {

  public currentCompany;

  public selectCompany(event: any, item: any) {

    this.currentCompany = item.name;
  }

}

And then on your template:

<tr *ngFor="let item of companies" (click)="selectCompany(item, $event)" 
 [class.highlighted]="item.name === currentCompany">

--

Another solution if you wish to have multiple highlighted companies you can add a property highlighted to your item. Then on selectCompany() you just set the property to true. On your check you do [class.highlighted]="item.highlighted".

Comments