How to add color to an HTML table depending on 3 different conditions

I have set 3 specific colors in my CSS. I have an HTML table and I am looking to have the background color of a cell change based on 3 conditions:

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

Here is my CSS:

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

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

And here is my HTML:

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

I initially attempted with 2 colors, but it only changed cells with the text 'True' to a red background. I have not worked with HTML in a while, but I recall this method working with numbers. I tried to search online but did not find a solution. Is there a way to achieve this with the 3 colors I have specified?

Answer №1

To achieve this goal, the conditional (ternary) operator can be utilized. For more information, refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

The code snippet below demonstrates the use of classes and {{ }} along with the ternary operator. If dict.status.includes('True') returns true, the class will be color-green. If dict.status.includes('False') returns true, the class will be color-red. Otherwise, the class will default to 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>

Answer №2

If you're looking to style elements dynamically, consider using the [ngClass] directive:

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

This allows you to assign classes to elements based on conditions.

Check out the playground link for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to combine the input tag's name with a growing integer variable?

Within a while loop, I need to modify the names of input tags by concatenating them with an increasing integer variable. However, attempts to use the $ symbol have not yielded successful results. <html> <head> <meta http-equiv="Content- ...

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...

Tips on displaying an avatar above and outside the boundaries of a background element using Chakra UI

They say a picture is worth more than a thousand words, and in this case, it holds true. The best way to illustrate what I'm trying to accomplish is through the image linked below. https://i.stack.imgur.com/5WvkV.png I envision having the avatar po ...

"Unlocking the Power of Ionic: A Guide to Detecting Status 302 URL Redirects

Trying to handle a http.post() request that results in a 302 redirect, but struggling to extract the redirected URL. Any tips on how to achieve this? Appreciate any help. ...

Determine the Placement of Bootstrap Popover by Utilizing SVG and Mouse Coordinates

Is there a way to dynamically reposition the popover that currently appears to the right of the Circle SVG? I would like to either base its position on the user's mouse click within the CircleSVG or move it to the exact center of the SVG, including bo ...

slow loading background slideshow in css

Creating a simple slideshow for the background using CSS has been successful, but I am facing an issue with making all backgrounds utilize background-size: cover. I want the images to fit properly on the screen. Another problem is that the pictures take a ...

Pass the form data to the next page with javascript in HTML

While working on a website for a power plant, I encountered some issues that require assistance. The main problem is that our client does not want to set up a database on their server. This means I can only use html, javascript, and a bit of php. There is ...

What is the best method for accessing a value in IndexedDB while utilizing service workers?

I am feeling overwhelmed by the concepts of IndexedDB and serviceworkers as I try to transform them into a functional application. Despite my extensive research, including studying various examples, I am struggling to integrate the two technologies effecti ...

The function onClick in Chart.js allows for passing the selected object in Typescript

In the documentation for Chart.js, I found a reference to an onClick function that is triggered whenever a click event occurs on the chart. The code snippet provided looks like this: options: { onClick: this.Function } Function(event, array){ ... } ...

What is the best way to include overflow-hidden in the image displayed by the tailblock component?

I have implemented the following Tailblock component, which is built on tailwind.css. My goal is to achieve a hover effect where the image scales up within its original dimensions. I want the image to zoom in without changing its height and width. I atte ...

Ways to gradually transition gradient color when hovering?

I am trying to modify the color of a linear-gradient() smoothly upon hovering, similar to how a solid color changes. I searched on w3schools and the Mozilla network for a solution but couldn't find anything. I attempted to apply the transition propert ...

Adjust the flex box height to match the dimensions of the image container

Currently, I am in the process of constructing a chat message layout and I am facing a challenge where I need to incorporate an image within a text bubble. The width of the bubble is fixed, but the height should adjust based on the aspect ratio of the imag ...

What could be causing the inaccuracies in the way my Array data is being transferred to my MySQL

Recently, I had the opportunity to learn how to convert a JSON file into an array with the help of a generous stackoverflow user. The process was successful, but when I attempted to input this data into my database, I encountered unexpected results. Array ...

Issue with Angular 2 AOT Compilation when trying to access formArray

This is the formGroup I created this.createOrderForm = this.fb.group({ items: this.fb.array([]) }); To add an item on button click addItem() { const control = <FormArray>this.createOrderForm.controls['items']; const a ...

Animate the smooth transition of a CSS element when it is displayed as a block using JQuery for a

I have implemented the collapsible sections code from W3 School successfully on my website. Now, I am trying to achieve a specific functionality where the "Open Section 1 Button" should slide down with a margin-top of 10px only if the first section "Open S ...

Error in Angular Template Parsing Due to Dynamic Object Key in Angular Version Greater Than 2

When I attempt to assign a value for a key with a variable inside my event binding expression, an unexpected error occurs: Parser Error: Unexpected token [, expected identifier, keyword, or string at column... https://i.sstatic.net/l3Fl5.png the expression ...

Does Google's caching process differ when using <span> tags instead of <h> tags for headings?

Does the choice between using <span class="heading"> and <h> tags impact search engine optimization for Google? As I'm constructing a website, I decided to style the headings and subheadings with <span>. However, I began to wonder i ...

Issue arising from swiper version 8 compatibility with angular version 16

After upgrading my Angular application to version 16 and implementing swiper version 8, I encountered errors when running the build:ssr command. The specific error message I received was: ./src/app/modules/pages/enterprise-price-list/enterprise-price-list. ...

Restrict printing loops within the designated division layer

Is there a way to limit the number of rows displayed horizontally when using foreach? I only want to display 7 rows. Can this be achieved with CSS or pagination? Here is an image illustrating the issue: https://i.sstatic.net/yJx3N.png Currently, it print ...

When adding my Angular web app to the home screen on iOS Safari, the icon appears as a screenshot instead of the specified apple-touch-icon

Despite adding an apple-touch-icon link to my index.html with a 150x150 PNG image, when I try to add my Angular web app as a shortcut to my iOS home screen from Safari, it only appears as a screenshot of the app page. Below is my HTML code: <!doctype ...