What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this?

Below is the code I am working with:

// JSON-EXAMPLE

{
    "success": true,
    "myJSON": {
        "myList": [
            {
                "id": 102000,
                "name": Alex,
                "age": 15
            },
            {
                "id": 10200, // length 5
                "name": Peter,
                "age": 30
            },
            {
                "id": 12345, // length 5
                "name": Andrew,
                "age": 34
            },
            {
                "id": 31322323,
                "name": Clark,
                "age": 40
            },
        ]
    }
}

// TS

public highlightedSpecialRows = null;

private loadData() {
    this.myService.getData(param).subscribe(
        (resp: any) => {
            const data = resp.success ? resp.myJSON.myList : null;
            if (null !== data && data) {
                .....
                const filterIdLength = 5; 
                this.highlightedSpecialRows = data.filter((d) => `${d['id']}`.length >= filterIdLength); 
            }
        }
    );

}

// HTML
<td mat-cell *matCellDef="let row; let i = index;" [ngClass]="{ 'highlightedRows': this.highlightedSpecialRows }">....</td>

Answer №1

If you want to add a class to each cell, you can use the following code snippet. It utilizes a simple class and method for this purpose.
CSS:

.one {color: red}
.two{color: yellow}
.three { color: green}
.fourorabove { color: blue}

HTML:

<ng-container >
        <td mat-cell *matCellDef="let element" [ngClass]="myClass(element)"> 
          {{element[column.id]}}
        </td>
</ng-container>

TS:

myClass(element){
    if(element['id'].toString().length=='1'){
      return 'one';
    }
    else  if(element['id'].toString().length=='2'){
      return 'two';
    }
    else  if(element['id'].toString().length=='3'){
      return 'three';
    }
     else  if(element['id'].toString().length>='4'){
      return 'fourorabove';
    }
  }

NOTE: Feel free to explore the demo link on STACKBLITZ.

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

Deleting validation messages from my MVC controls

I set up some validation in my Model by adding the following code: [Required] [StringLength(60, MinimumLength = 4)] [Display(Name = "Users code")] public string UserCode { get; set; } When c ...

Update the gulp watch function to use gulp@4

We are currently in the process of transitioning from <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb9c8e978bbbc8d5c2d5ca">[email protected]</a> to gulp@4, and encountering difficulties during the switch. Upon r ...

Creating a Form Input Field Based on a Selection List

I'm in the process of developing a small app to boost my productivity at work. Currently, I have some html/js code that includes a ul with a search filter. When I select an option, it opens a new tab with relevant text. Ideally, I want the outcome to ...

Unable to capture user input text using $watch in AngularJS when applied on ng-if condition

I have developed a cross-platform application using AngularJS, Monaca, and OnsenUI. In my login view, I check if the user has previously logged in by querying a SQLite database. Depending on whether there is data in the database, I either display a welcom ...

How can I change "Thu Sep 19 14:24:59 UTC 2019" into a moment date?

Struggling to convert this date: created_at= "Thu Sep 19 14:24:59 UTC 2019" I attempted to use the following code: let elementDate=moment(created_at) However, I keep receiving an error message: moment.invalid(/* Fri Aug 30 09:52:04 UTC 2019 */) I als ...

Utilizing React JS: Displaying or Concealing Specific Components Based on the URL Path

Is there a way to dynamically change the navbar items based on the URL without having separate navbar components for each side? My current navbar design features 3 links on the left side and 3 links on the right, but I want to display only one side at a ti ...

Rails controller did not receive the Ajax call

I have noticed that when I make an Ajax call using jQuery, the data is always transmitted (status 200), but there are times when it's not properly received by the Rails controller. The data is sent correctly, but most of the time the controller respon ...

Tips for passing a JavaScript array to an MVC controller

In my asp.net application, I have implemented a functionality where users can order food. Additionally, there is an admin page where admins can login and create a menu for a specific week. I have successfully developed the "Menu maker" feature where all me ...

It is not possible to trigger an input click programmatically on iOS versions older than 12

Encountering a challenge in triggering the opening of a file dialogue on older iOS devices, particularly those running iOS 12. The approach involves utilizing the React-Dropzone package to establish a dropzone for files with an added functionality to tap ...

Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated! Permission.ts (This is the Permission model file. It has references with the Module model ...

Display or conceal toggle in ruby utilizing jQuery

I'm facing an issue with the functionality of a button that is meant to hide and show a form using jQuery. Initially, I added a path to signup in the button so that it would display and function properly. Now, when I click the button, the form shows u ...

What can be done to ensure that two separate react-native Picker components do not interfere with each other's

Encountering an issue with two Pickers in a react-native View. Whenever I select a value in one Picker, it causes the other Picker to revert back to its initial item in the list. It seems like the onValueChange function is being triggered for both Pickers ...

Connecting to a port in node.js is not possible

Currently, I am using port 4200 for my Angular application and port 3000 for my Node.js server. However, I am facing an issue where when I run the Angular application, the Node.js server does not work and I encounter a "Connection refused" problem. Can a ...

Implementing Dropzone in an Angular MVC5 project

For more information about dropzone, visit this link I am currently implementing dropzone as my file upload handler with the combination of angularjs and MVC5. The challenge I'm facing is getting the Http post request to go from the angularjs servic ...

Unable to set background-image on Node (Limited to displaying only images sourced from Flickr)

I am experiencing difficulty with the background-image node property not functioning properly. In order to test this issue, I am using the "Images & breadthfirst layout" demo as an example (accessible at https://gist.github.com/maxkfranz/aedff159b0df0 ...

Struggling to incorporate JSON data and javascript functions into an HTML file

I've been struggling to create a feed from a json link and display it in separate divs within an html document. Despite multiple attempts with different approaches for three different newspaper sources, I have not been successful. I'm hoping som ...

CSS transition fails to revert

My standard opacity animation is not working in reverse order. Here is a link to the JSFiddle example. According to the documentation, it should work automatically. Since I am new to JavaScript, I am unsure if this issue lies in my code or if the CSS anima ...

Posting data from an Angular 2 frontend to an Express server: A step-by-step

Seeking guidance as a beginner trying to understand the process of sending contact form data from Angular 2 to a Node/Express server. Currently, I have Angular 2 hosted on localhost:4200 and the express server running on localhost:3000. However, when attem ...

How can a default value be assigned to an ag-Grid filter?

Is there a way to set a default value in ag-grid filter text that is displayed to the user but not applied to the actual results? this.columnDefs = [ { headerName: this.pageData["tbm.line.list.grid.phonenumber"], field: 'tn', /*sor ...

Angular8's NgFor directive is designed to bind to Iterables like Arrays only

Having an issue retrieving data from Github and displaying it, as I am encountering errors. The code editor is highlighting an error with "followers" in the github-followers.component.ts file. githup-followers.component.html <div *ngFor="let follower ...