Search code examples
angularng-class

styles being applied to all tr angular2


I am trying to apply background-color with [ngClass] on a table tr. Styles are getting applied but they are changing all tr's background-color. I want it to be specific to only the one that is being clicked.

Here's my code:

component.html

  <tr *ngFor="let entitydata of extractData" [ngClass]="{'backcolor':selected}" (click)="select(entitydata)">
                  <td>{{entitydata.clientname}}</td>
                  <td>{{entitydata.partner}}</td>
                  <td>{{entitydata.risk}}</td>
                  <td>{{entitydata.evaluationid}}</td>
                  <td>{{entitydata.status}}</td>
                  <td>{{entitydata.approvedondate}}</td>
              </tr>

component.ts

export class Component{
public selected:boolean=false;
select(entitydata){
        this.selected =  this.selected===true ? false : true;
    }
}

component.css

.backcolor{
    background-color:green;
}

Thanks for any help.


Solution

  • Here it is , I got your point by this you can manage what you exactly want

    In your template :

    <tr *ngFor="let entitydata of extractData" [ngClass]="{'backcolor': selectedEntity === entitydata }" (click)="select(entitydata)">
        <td>{{entitydata.clientname}}</td>
        <td>{{entitydata.partner}}</td>
        <td>{{entitydata.risk}}</td>
        <td>{{entitydata.evaluationid}}</td>
        <td>{{entitydata.status}}</td>
        <td>{{entitydata.approvedondate}}</td>
    </tr>
    

    In your component :

    selectedEntity = {};
    select(entity)
    {
        this.selectedEntity = entity;
    
    }