简体   繁体   中英

Color html table based on 3 conditions

I have 3 colors defined in CSS. In HTML i have table and I want the backdround color of a cell to change based on 3 conditions:

 if cell contains the text 'True'     - color green
 if cell contains the text 'False'    - color red
 if the cell contains the text 'None' - color yellow

my css:

.color-green {
    background-color: green;
    color: black;
  }

  .color-yellow {
    background-color: orange;
    color: black;
  }
  
  .color-red {
    background-color: red;
    color: black;
}

my html:

<td ng-class = "{'color-yellow':dict.status='True','color-red':dict.status=='false'}">{{ dict.status}}</td>

I tried with 2 colors first, but this just changes my cells to True with red backround. I haven't touched html in a long time but i remembered this method worked with numbers. Tried to google but not so lucky:(

Is there any way of doing what I want with the 3 colors?

I thinks you can try with the directive [ngClass]:

<td [ngClass] = "{'color-yellow':dict.status='true','color-red':dict.status=='false'}">{{ dict.status}}</td>

Where you can assign class to an element using it.

Playground link

The conditional (ternary) operator can use for this goal. More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

The following code is using class and {{ }} then using ternary operator. if dict.status.includes('True') returns true then class is equal to color-green else if dict.status.includes('False') returns true then the class is equal to color-red and else class becomes color-yellow .

class = "{{ dict.status.includes('True') ? 'color-green' : dict.status.includes('False') ? 'color-red' : 'color-yellow' }}

 .color-green { background-color: green; color: black; }.color-yellow { background-color: yellow; color: black; }.color-red { background-color: red; color: black; }
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <div ng-app=""> Type your text in this box: <input type="text" ng-model="dict.status"> <table> <tr> <td class = "{{ dict.status.includes('True')? 'color-green': dict.status.includes('False')? 'color-red': 'color-yellow' }}">{{ dict.status}}</td> </tr> </table> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM