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

The functionality of "Priority Nav" is compromised when a div is floated

I am currently utilizing the "Priority Navigation" design technique. This means that when the viewport width is reduced and there isn't enough space for all the list-items to fit horizontally, they are moved into another nested list under a "more" lin ...

Locate and retrieve all the records that contain an asterisk symbol in MongoDB

Could someone provide assistance with finding documents in MongoDB that contain the '*' character using regex? For example, the following regex (db.collection.find{value: new Regex('*')}) should retrieve all documents with '*&apos ...

TypeScript abstract class generics: `Class<?>` type

When working with TypeScript, I often utilize a Java-like type called Class: interface Class<T = void> { new(...args: any[]): T; } Unfortunately, this type doesn't seem to be compatible with abstract classes: abstract class Bar {} class ...

Guidelines on concealing the parent component while the child component is loading in Angular 2

In my latest project, the view setup is as follows: Upon page load, the Parent Item Description should be visible while the Selected sub item description remains hidden. When a Sub Item x is selected, the Parent Item Description should disappear and only ...

"Implementing an abstract method in a class by overloading it with a generic type that

// Greetings from the TypeScript Playground, a platform where you can experiment with TypeScript code. type Constructor<T> = new (...args: any[]) => T; class ServiceChecklistResponse { } class AnotherModel { } abstract class AbstractView { ...

"Using PHP to encode an array into JSON format might result in additional

My PHP array needs to be printed as clean JSON, but I'm encountering issues with extra quotes. While the current JSON output is technically valid, it's not formatted how I want it to be. Below you can see the original PHP array, the json_encode o ...

JavaScript - retrieve only the domain from the document.referrer

I am trying to extract only the domain from referrer URLs. Two examples of referrer URLs I encounter frequently are http://www.davidj.com/pages/flyer.asp and http://www.ronniej.com/linkdes.com/?adv=267&loc=897 Whenever I come across URLs like the ones ...

The custom server was functioning properly, but as soon as I altered the file directory, an error occurred on Next.js

After creating "create-next-app," I successfully set up the folder structure as follows: +client2 --.next --node_modules --public --... --server.js However, when I move my "server.js" file to a different location: +client2 --.next --no ...

Can one retrieve a catalog of Windows Updates that have been installed by utilizing node.js?

Currently, I am working on a JavaScript/Node.js project where I am seeking to retrieve a comprehensive list of all installed windows updates, similar to how it is done using the C# WUAPI 2.0 Type Library. I have attempted utilizing WMI calls (specifically ...

When attempting to perform conditional rendering in React using a stateless functional component, I encounter an error stating "Unexpected token, expected ,"

Here is the code snippet: 'use strict' import React from 'react' import { connect } from 'react-redux' import { Panel, Col, Row, Well, Button } from 'react-bootstrap' const Cart = ({ cart }) => { const cartI ...

Deciding on the proper character formatting for each individual character within the RICHT TEXT EDITOR

After browsing numerous topics on Stackoverflow, I was able to develop my own compact rich text editor. However, one issue I encountered is that when the mouse cursor hovers over already bold or styled text, it's difficult for me to identify the styl ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

The ngx-translate Angular translation file is being loaded twice unnecessarily

Upon reviewing the network tab in the browser's developer tools, I discovered that my Angular app translation file is being loaded twice. Is there an issue with this? Should it be loading multiple times? https://i.stack.imgur.com/vcKm1.png ...

In search of a simple solution for parsing JSON efficiently

I'm currently working on parsing JSON data using Java language: { "student_id": "123456789", "student_name": "Bart Simpson", "student_absences": 1} Can someone suggest a more efficient method to achieve this? I have attempted the code below but feel ...

Using React for Right-to-Left (RTL) Support

How can RTL (Right-to-Left) support be effectively implemented in React applications? Is there a method to customize default <p> and <span> components for RTL support without the need to rewrite existing components? For instance, using a global ...

utilizing the active class with react js

Apologies for the question, but I am facing an issue where adding an active class to a button is affecting all buttons when clicked. How can this be fixed? Here is the code snippet: <div className=""> {category.items.length === 0 ? ( ...

Crack the code of regular expressions and convert it into a dictionary

Python string contains a regex string I'm trying to decode the given string and store it in a dictionary However, I'm facing difficulties in decoding them from unicode. Is there a solution for this issue? Thank you! import json example = """ ...

Having trouble reaching the elements stored in an array?

As a beginner in Angular and JavaScript, I may be making some obvious mistakes so please bear with me. I have written this code that allows the selection of 2 text files and then combines them into a single array. $scope.textArray = []; $scope.textUpload ...

Looking for the quickest hash and salt method for IP addresses in Node.JS?

Currently, there are many stipulations regarding the tracking of user data such as unique visits and returning users. An issue arises in certain regions where IP addresses are considered sensitive personal information. To continue identifying unique user ...

Is there an improved method for designing a schema?

Having 4 schemas in this example, namely Picture, Video, and Game, where each can have multiple Download instances. While this setup works well when searching downloads from the invoker side (Picture, Video, and Game), it becomes messy with multiple tables ...