Drew13 Drew13 - 19 days ago 6
TypeScript Question

Revert element's background color when clicked again

Using Angular 2, I have a table with striped rows and when I click a row it turns green and only one row can be green at a time. I want to add the functionality that if a row that is currently clicked on (turned green) is clicked again, it reverts back to the color it was before originally being clicked. Right now a row will only revert back to its original color if a different row is clicked.

Table without any rows clicked:
enter image description here

Table when the second row is clicked:
enter image description here

HTML grey is #d3d3d3. Green is #015939:

<tr *ngFor="let dPoint of theData; let idx=index; let even=even" (click)="onClick(dPoint, idx)" (row)="received($event)" id="{{dPoint.tDataPoint}}"
[style.backgroundColor]="clickedRow == idx ? '#015939' : (even ? 'white' : '#d3d3d3')" [style.color]="clickedRow == idx ? 'white' : '#015939'">
<td>{{dPoint.tDataPoint}}</td>
<td>{{dPoint.tICCP}}</td>
<td>{{dPoint.tStartDate}}</td>
<td>{{dPoint.tEndDate}}</td>
</tr>


Typescript:

onClick(message:DataTable, idx:any){
this.clickedRow = idx;
//more code that isn't relevant to this functionality
}

Answer

Just set idx to a non-existing index to make no row selected:

onClick(message:DataTable, idx:any){
  if(this.clickedRow == idx) {
    this.clickedRow = -1;
  } else {
    this.clickedRow = idx;
  }
  //more code that isn't relevant to this functionality
}