asaf david
asaf david

Reputation: 13

angular change td back gound color if by value

there was only angularjs for this and it didnt work for me
trying to set the td back ground color if type ==1 ( can be 1 or 2)
the html of my angular

 <div *ngIf="truck" style="overflow-x:auto;">
       <table border = "1" >
        <tr>   
         <th>truckid</th>
         <th>year</th>
         <th>type</th>
         <th>1</th>
         <th>2</th>
         <th>3</th>
         <th>4</th>
         <th>5</th>
         <th>6</th>
         <th>7</th>
         <th>8</th>
         <th>9</th>
         <th>10</th>
         <th>11</th>
         <th>12</th>
        </tr>
        <tr *ngFor="let tobj of truck">
    
         <td>{{tobj.truckid}} </td>
         <td>{{tobj.year}}</td>
         <td> {{tobj.type}} </td>
          <td *ngFor="let t1 of tobj.arr">
              {{t1.income}}</td>
        </tr>  
      </table>
    </div>

tryd this: Change HTML table cell background color using Angular JS
but did not work for me
new to angular 😉


**update:**
my css:
table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {background-color: #f2f2f2;}

.red {
  color: red;
}

.black {
  color: black;
}
.some-class {
  background-color: #ff2244;
  }

Upvotes: 0

Views: 981

Answers (2)

Mohamed Niyaz
Mohamed Niyaz

Reputation: 218

We can have something like below:

<div *ngIf="truck" style="overflow-x:auto;">
       <table border = "1" >
        <tr>   
         <th>truckid</th>
         <th>year</th>
         <th>type</th>
         <th>1</th>
         <th>2</th>
         <th>3</th>
         <th>4</th>
         <th>5</th>
         <th>6</th>
         <th>7</th>
         <th>8</th>
         <th>9</th>
         <th>10</th>
         <th>11</th>
         <th>12</th>
        </tr>
        <tr *ngFor="let tobj of truck">
    
         <td>{{tobj.truckid}} </td>
         <td>{{tobj.year}}</td>
         <td [ngClass]="getColorCode(tobj.type)"> {{tobj.type}} </td>
          <td *ngFor="let t1 of tobj.arr">
              {{t1.income}}</td>
        </tr>  
      </table>
    </div>

And at ts file , define the method like below :

def getColorCode(type) {
 if(type==1 || type==2) {
    classname = "<some-color-as-class>"; // some-color-as-class is a placeholder:)
 } 
 return classname;
}

And at css , define below code:

<some-color-name-as-class> {
  color: red; // as per your wish
}

Upvotes: 0

user13258211
user13258211

Reputation:

You can set the style.backgroundColor property of the element directly, or conditionally add a class using ngClass

Direct:

<td [style.backgroundColor]="tobj.type === 1 ? '#FFFFFF : #000000'"> {{tobj.type}} </td>

NgClass:

<td [ngClass]="{ 'some-class': tobj.type === 1 }"> {{tobj.type}} </td>

CSS with ngClass Example:

.some-class {
background-color: #FFFFFF;
}

Upvotes: 2

Related Questions