How can we assign various class names depending on the value of an object?

I have a set of objects stored in my component. I need to dynamically apply different classes based on the value of the ErrorLevel property within each object. If an object has ErrorLevel equal to 1, I want to assign the following classes to various elements:

class-red
class-container-red
class-message-red

If the ErrorLevel is not equal to 1, I would like to assign the following classes to the elements instead:

class-yellow
class-container-yellow
class-message-yellow

Is there a more efficient way to achieve this using Angular or CSS (or SASS) without having separate methods for each individual class?

Here is an example code snippet showcasing what I currently have:

<html>
<body>
<div *ngFor="let obj of myObjects">
<h1 [ngClass]="getCssClass(obj.ErrorLevel)"></h1>
<p [ngClass]="getCssClass2(obj.ErrorLevel)"></p>
<div [ngClass]="getCssClass3(obj.ErrorLevel)"></div>
</div>
</body>
</html>
export interface MyObject {
    Id: number;
    ErrorLevel: number;
}

@Component({
  selector: 'my',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
  @Input() myObjects: MyObject[];

  constructor() { }

  ngOnInit() {
  }

  getCssClass(errrorLevel) {
    if(errrorLevel === 1) {
      return "class-red";
    } else {
      return "class-yellow";
    }
  }

  getCssClass2(errorLevel) {
    if(errrorLevel === 1) {
      return "class-container-red";
    } else {
      return "class-container-yellow";
    }
  }

  getCssClass3(errorLevel) {
    if(errrorLevel === 1) {
      return "class-message-red";
    } else {
      return "class-message-yellow";
    }
  }
}

Answer №1

Here is a suggestion for styling your HTML elements using Angular syntax:

<div [class.class-red]="errorLevel === 1" [class.class-yellow]="errorLevel !== 1"></div>

This code will add the specified class based on the condition being true.

Alternatively, you can follow xyz's solution, but I personally prefer using the [ngClass] syntax as it tends to be more readable.

I want to point out that naming your CSS classes starting with "class-" is unnecessary since the period in CSS already indicates it is a class. Just use names like red instead of class-red.


For a more efficient approach, consider placing the class on the parent div rather than individual elements:

<div [class.red]="object.ErrorLevel === 1" [class.yellow]="object.ErrorLevel !== 1" *ngFor="let object of myObjects">
    <h1>...</h1>
    <p>...</p>
    <div>...</div>
</div>

Then use CSS to style the child elements based on the parent class:

.red h1 {
    // styles for red h1
}
.red p {
    // styles for red p
}
...
.yellow div {
    // styles for yellow div
}

This method is recommended for several reasons:

  1. Easier maintenance with one class applied to a single element, reducing the need to update multiple places when adding new color options.

  2. Improved readability by centralizing the styling logic in one location.

  3. Better performance as Angular only monitors changes on one element rather than multiple ones.

Answer №2

If your project requires managing more than 2-3 error color cases, I suggest the following approach:

interface IError {
   id: string;
   color: string;
}

var errors: { [id: string]: IError; } = {
   "e1": { id: "1", color: "class-red" },
   "e2": { id: "3", color: "class-yellow" },
   ...
   "en": { id: "n", color: "class-n" }
};

Then, you can proceed to implement the getValueById method.

UPDATE: You may consider implementing a similar solution like the one below. Please excuse any potential errors as this was written in notepad. :)

interface IErrors<T> {
    add(key: string, value: T): void;
    remove(key: string): void;
    containsKey(key: string): boolean;
    keys(): string[];
    values(): T[];
    errorClass(key: string): T;
}

class Dictionary<T> implements IErrors<T> {

    _keys: string[] = [];
    _values: T[] = [];

    constructor(init?: { key: string; value: T; }[]) {
        if (init) {
          for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
          }
        }
    }

    add(key: string, value: T) {
        this[key] = value;
        this._keys.push(key);
        this._values.push(value);
    }

    remove(key: string) {
        var index = this._keys.indexOf(key, 0);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);

        delete this[key];
    }

    keys(): string[] {
        return this._keys;
    }

    values(): T[] {
        return this._values;
    }

    containsKey(key: string) {
        if (typeof this[key] === "undefined") {
          return false;
        }

        return true;
    }
    errorClass(key: string): T {
        return this[_keys]._values;
    }
}

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

Tips for building an interactive button with changing content and retrieving variable information when the button is clicked in an Angular framework

Received dynamic data from the server is shown below: { "data": [ { "id": 4, "first_name": "Eve", "last_name": "Holt", "lat":"25.6599899", "lng":"45.3664646", "status":"0" ...

Tips for incorporating a PDF file into a website when the Adobe Reader add-on is disabled in Internet Explorer

I attempted to insert a PDF into my website using the <embed> tag. Unfortunately, it doesn't seem to be functioning properly in Internet Explorer when the Adobe Reader add-on is disabled. Is there a solution that will allow it to work even if th ...

Unable to apply styling to table cells that are dynamically added using JQuery within an Angular

Currently working on setting up a form using Angular. Within the hotel.view.html file, there is a table that looks like this: <table id="rooms"> <tr> <td>Room Type</td><td>Beds</td><td>Q.ty</td ...

It is not possible to submit a form within a Modal using React Semantic UI

I am working on creating a modal for submitting a form using React semantic UI. However, I am encountering an issue with the submit button not functioning correctly and the answers not being submitted to Google Form even though I have included action={GO ...

Learn how to manipulate the DOM by dynamically creating elements and aligning them on the same line

Providing some context for my page: The section I have always contains a single input field. Below that, there is an "add" button which generates additional input fields. Since only one field is required on the screen, the following fields come with a "de ...

Error in Visual Studio when attempting to create a new Angular file without proper authorization

After setting up node, npm, and angular cli, I encountered an UnauthorizedAccess error when creating a new project in Visual Studio. Can someone please offer some assistance? Thank you, Please see the attached error image for reference ...

Create a versatile multi-autocomplete-chips input in Angular 9 using FormArray and encounter the issue: ERROR TypeError: control.registerOnChange is not a

Current Situation Table component - a table with buttons to create or edit rows. Clicking on any of these buttons will open the same Dialog component containing an input field. The input field is a reusable multi-autocomplete-chips component. If the user ...

Assist the floats to "ascend" and occupy the available space

The screenshot showcases boxes that have been styled with "float: left". Is there a way to make these boxes float to the first available space in a column? For example, can we move the Music Nation box to the location indicated by the red arrow in the ima ...

The stylesheet link for "contact.css" is unresponsive

I have been reorganizing my website portfolio by categorizing CSS, images, and other files into different folders. <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/contact.css"> However, I am facing an issue where ...

What is the best way to create an animation where every letter in a word transitions to a different

Is there a way to animate a word so that each letter changes color within a range of 7 colors, with all letters displaying different colors simultaneously in an infinite loop? <div class="box"> <h1 class="logo animate__animated an ...

Angular Firebase Email Verification sent to an alternate email address

I am facing a challenge with my website that only accepts emails from a specific domain, such as a university domain. Users who want to sign up using Facebook or Google need to verify their university email, but I am struggling to find a way to send the ve ...

Modifying jQuery CSS causes certain CSS rules from a file to be deleted

When using jQuery to change the css of an element, I've noticed that it can remove some previously specified css rules for that element. For example, .className, .className2, etc... { background-color: black; color : silver; } .className: ...

Dropdown menu will appear when you click on one of the menu items

Can someone help me create a dropdown menu using a JavaScript function that toggles on click? I've attempted to do so with the following code, but it's not working as expected. Could you please point out where I might be going wrong? I'm loo ...

What could be causing my CSS parallax effect to not work as expected?

I have been attempting to implement the parallax image technique following the Keith Clark tutorial, but I am facing difficulties in getting it to work correctly. Utilizing the skeleton CSS framework, my goal is to recreate an existing website in order to ...

Easily transform a CSS file for optimal use on dark backgrounds from scratch

I've got around 200 CSS files that look like this: /** * GeSHi Dynamically Generated Stylesheet * -------------------------------------- * Dynamically generated stylesheet for bnf * CSS class: , CSS id: * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 ...

What is the best way to implement a seamless left-to-right sliding effect for my side navigation using CSS and Javascript?

I am currently working on creating a CSS and JavaScript side navigation. Below is the code that I have implemented so far: var nav = document.getElementById('nav'); function show(){ nav.style.display = "block"; } .side-nav{ background-color:bl ...

Utilizing localstorage data in angular 2: A comprehensive guide

Is there a way to utilize data stored in localstorage for another component? This is what the localstorage service looks like: localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success, res: res.data })); I am inte ...

Pictures Unavailable to Show in Table

I've been working on a project where I need to insert some images into a table. Usually, this isn't an issue for me. However, today when I added the images to the table, all I see is a square border with the alt text inside it. I'm confident ...

Manipulate the CSS of a single div within a group of divs that have the same class using jQuery

I'm attempting to modify the CSS of a specific DIV that shares its class with other divs. I've searched for a solution but haven't had any luck so far. Here is the code I've been using without success: $(".singleOffer").click(functio ...

Floating division element above responsive divisions

element, I am in the process of developing a straightforward online card interface. In this interface, there will be a user profile picture displayed above some details about that user. However, to achieve this layout, the profile picture must appear hove ...