Drew13 Drew13 - 1 year ago 88
HTML Question

Check if tr is an even or odd row to toggle background color in striped table

I'm trying to toggle the background color of some

elements based on the background color they are when clicked. This is simple when not working with a striped table. Essentially, the table starts out like the screenshot below. If I click on a row I want to change it to the green hex color I have in my if statement, and if I click it again I want to change it back to the color it was before initally being clicked.the table

Right now this will change any row that is clicked to the green color, but when clicked again it changes it to white regardless of what color it was before being clicked the first time:

onClick(message:DataTable, idx:any){
var rowClicked = <HTMLCanvasElement> document.getElementById(message.tDataPoint);
var rowColor = rowClicked.style.backgroundColor;
if (idx%2===0 && rowColor === "#015939"){
} else if (idx%2===1 && rowColor === "#d3d3d3") {
} else if (idx%2===0 && rowColor === "white") {
} else if (idx%2===1 && rowColor === "#015939") {

HTML to generate table:

<tr *ngFor="let dPoint of theData; let idx=index" (click)="onClick(dPoint, idx)" (row)="received($event)" id="{{dPoint.tDataPoint}}">

If there's a way in Typescript to check if the row is even or odd, then I can just write the proper if statement's to change the color based on that.

UPDATE I edited my function

Answer Source

If you generate it using *ngFor you can use these predefined values Implementing ngClassEven ngClassOdd for angular 2, or you can just pass the index with the click`

<tr *ngFor="...; let idx=index; let even=even" 
    [style.color]="rowClicked == idx ? 'green' : (even ? 'white' : 'grey')"
onClick(idx) {
  this.rowClicked = idx;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download