Using Angular ngClass with a conditional statement

Incorporating data from a JSON file instead of a database, my goal is to assign a color to the icon based on the status value in the JSON. For instance, [if green? class1:class2]. Here is the code snippet I am working with:

My HTML file

   <ng-container matColumnDef="status" [ngClass] = "{'color1': row.status === 
        'GREEN', 'color2': row.status === 'RED'}">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Status</th>
        <td mat-cell *matCellDef="let row" class="color1">{{row.status}}</td>
        <td mat-cell *matCellDef="let row" class="color2">{{row.status}}</td>
    </ng-container>

Below is my JSON file.

    data:[
          {
           "name": "xyz",
           "address": "post",
           "status": "GREEN"
          },
          {
           "name": "xyz1",
           "address": "post1",
           "status": "RED"
           }
         ],
       "count" : 2
}

This is my CSS

.color1{
  color: green;
}

.color2{
  color: red;
}

** Facing an issue where I am unable to change the color of the status icon and encountering the following error **

ERROR TypeError: Cannot read property 'status' of undefined

Answer №1

When using ngClass, you provide an object with key-value pairs where keys are possible classes and values are the conditions for applying those classes.

To ensure static checking for all possible class values, you can do something like this:

 <td mat-cell *matCellDef="let row" class="color1"
     [ngClass]="{
     'green': row.status === 'GREEN',
     'red': row.status === 'RED'">{{row.status}}</td>


Another approach for the same concept is:

<td mat-cell *matCellDef="let row"
[class.red] = "row.status === 'RED'"
[class.green] = "row.status === 'GREEN'" >
{{row.status}}
</td>

An alternative method is to use a map object in your TypeScript file to define classes and access them in the HTML like this:

mapClass = {
  'GREEN': 'green',
  'RED': 'red' 
}

And in the HTML:

 <td mat-cell *matCellDef="let row" class="{{mapClass[row.status]}}">{{row.status}}</td>

The last method is more efficient if your possible class values change frequently. By updating the mapClass object, you can easily add new possible values and their corresponding CSS classes without changing the HTML structure.

EDITING: Based on your updated question, it seems there might be an issue with using ngClass within an ngContainer. Make sure to apply ngClass directly to the td element instead. Additionally, if you have multiple td elements with different classes within a container, consider using ngIf directives to display the row status accordingly.

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

Having issues with autocompletion in the input element of Angular 7 Material Design

My Angular 7 application includes a Material Design form with input text fields, and I have not implemented any autocomplete feature within the code. Despite deleting all navigation data from my Chrome browser, I am still experiencing autocomplete suggesti ...

JavaScript class name modifications are not functioning as expected

Testing a sprite sheet on a small web page I created. The code for each sprite in sprites.css is structured like this... .a320_0 { top: 0px; left: 0px; width: 60px; height: 64px; background: url("images/sprites.png") no-repeat -787 ...

Is there a way to embed an AJAX submit form into a notification without the need for page refresh?

I have integrated the jQuery plugin toastr js () for notifications on my website. I am facing an issue where I want to include a contact form within the notification popup and submit it using AJAX. Despite having the form working fine outside of the toastr ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

Variations in CSS behavior for select and option elements

I have implemented the following HTML code snippet: <select ...> <option value=""></option> <option data-ng-repeat="type in xy" value="{{type.name}}" ng-style="{'border-left': '4px solid '+ type.color, &apos ...

What are the steps to integrate jQuery into an Angular 8 application?

I am currently working on an application that relies on SignalR for communication with a desktop application. In order to make use of SignalR, I include jQuery in my .ts file. However, after migrating from Angular 7 to Angular 8, it appears that this setup ...

Is it possible to substitute responsive image placeholders with corresponding CSS for div containers?

I have successfully implemented the desired design using HTML and CSS, but I am currently using image placeholders. I am seeking to achieve a similar effect with CSS for div elements instead of images. <div class="item-box">{{ item.title }}</div ...

Efficiently rearranging elements by adjusting their top values techniques

My iPhone lockscreen theme features various elements displaying weather facts such as text and small images. Currently, these elements are positioned in the middle of the screen and I want to move them all to the top. Each element has a unique position abs ...

The button must be programmed to remove a specific item from the server

I am currently developing an application to monitor my expenses using javascript, nodejs, express, and handlebars as the templating engine. Within the app, I have a "list" div that displays all of my expenses. (There is an add button next to the list, not ...

Issue with Ionic2 radio button selection not persisting

I'm currently working on implementing Radio Alerts within an Ionic2 application. To create a radio alert, I used the following code snippet: let alert = this.alertCtrl.create(); alert.setTitle('Select a Radio Alert'); alert.addInput({ typ ...

Tips for aligning text alongside ons-select elements

I am working with the following HTML snippet: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsenui.css"> <link rel="stylesheet" href="https://u ...

Guidelines for retrieving a file from Amazon S3 through a web browser utilizing Python (and boto) on Google App Engine

I have a Python program running on Google App Engine using boto 1.9b that retrieves all keys from an S3 Bucket and formats the output into an HTML table. bucket_instance = conn_s3.get_bucket(bucketname) liste_keys = bucket_instance.get_all_keys() table = ...

Is Bootstrap CSS Carousel malfunctioning following a float adjustment?

Currently, I am trying to implement a carousel in bootstrap, but I am facing two significant issues. The alignment of the carousel is vertical instead of horizontal (my div elements are stacking downwards). When I apply the float: left property, the carou ...

Exploring the potential of HTML5 canvas for speedy pixel manipulation

Is there a method to interact with canvas pixels in real-time without using getImageData or createImageData due to their slow performance? ...

"There seems to be an issue with the KeyListener function in

The error I'm encountering is: index.html:12 Uncaught TypeError: Cannot read property 'addEventListener' of null I'm unsure about what went wrong. The intention behind the code was to store the result of the selected radio button into a ...

What is the best way to paste plain text into a Textarea without any formatting?

A challenge I am facing in my project is related to copying and pasting text into a Textarea. When a user copies text, the style of the text is also inserted along with it. However, when the user manually types the text, it gets inserted correctly without ...

Utilizing nested createHtmlOutputFromFile in Google Apps Script HtmlService to generate jQuery code

Embarking on a new journey, I am diving headfirst into the world of JQuery WebApp with Google Apps Script. Every day is filled with new discoveries and excitement as I immerse myself in learning to piece things together. Starting off with some examples an ...

Unable to view sidebar navigation on the screen

I've been experimenting with the sidebar navigation from w3 schools, specifically trying to create a side-nav that opens from one div. You can see an example here: http://www.w3schools.com/w3css/tryit.aspfilename=tryw3css_sidenav_left_right&stack ...

Submenu in submenu not registering CSS hover events

Currently, on a website project that I'm developing, there is a submenu nested within another submenu. Interestingly enough, the level-2 submenu happens to be taller than its parent level-1 submenu. To control the visibility of these submenus, I' ...

Angular Material date picker input assumes that the date is in US format

While entering the date manually in the input field (without using the datepicker), the date format defaults to US format. For instance, if you type in "10/01/2019" in the input field, it changes to "01/10/2019" and when you open the date picker, it displa ...