如何突出显示* ngFor中的选定行?

时间:2016-11-02 11:14:46

标签: css twitter-bootstrap angular html-table

我找不到能帮助我在Angular2中解决这个问题的东西。当我选择一行时,我想设置一个css类。 (不使用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> 

我正在使用Angular2最终版本

2 个答案:

答案 0 :(得分:18)

有很多解决方案可以做到这一点,其中一个是您可以在点击时存储当前公司。

*ngFor中,您检查当前项目是否为currentCompany,并添加课程highlighted或您希望同一公司的任何课程。

export class TableComponent {

  public currentCompany;

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

    this.currentCompany = item.name;
  }

}

然后在你的模板上:

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

-

另一种解决方案,如果您希望拥有多个突出显示的公司,则可以在项目中添加属性highlighted。然后在selectCompany()上,您只需将属性设置为true即可。在您的支票上,您执行[class.highlighted]="item.highlighted"

答案 1 :(得分:0)

我知道这是在不久前回答的,但是要扩展接受的答案,您还可以使用[ngClass] =“ {'class_name':item.id === currentCompany}”。可能需要删除表格悬停,因为它可能隐藏背景颜色更改

NLog.config

然后是CSS

<tr *ngFor="let item of companies" (click)="selectCompany($event, item)" [ngClass]="{'class_name': item.id === currentCompany  }" >