Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 959
Mourad Idrissi Avatar asked Nov 02 '16 11:11

Mourad Idrissi


1 Answers

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($event, item)" 
 [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".

like image 176
Joel Almeida Avatar answered Oct 19 '22 09:10

Joel Almeida