"Angular 6: A Guide to Customizing Text Colors Based on Status

I have a view on angular just like this:

https://i.sstatic.net/JimWN.png

And this is my dashboard.component.ts:

 export class DashboardComponent implements OnInit {
 tablePresetColumns;
 tablePresetData;
 ngOnInit() {
   this.tablePresetColumns = [{id: 1,content: 'Username'},{id: 2,content: 'Status'}];
   this.tablePresetData = [[{id: 1,content: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33595c5b5d1d575c567341525d575c5e1d505c5e">[email protected]</a>'},{id: 2,content: 'Busy'}],[{id: 1,content: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98d9c8a8dcbb98b98979d9694d79a9694">[email protected]</a>'},{id: 2,content: 'overload'}]];
  }
 } 

And this is the way i call the table on dashboard.component:

<div eds-tile class="xl-4" style="height: 700px">
    <eds-tile-title>User on Shift</eds-tile-title>  
    <eds-table [columns]="tablePresetColumns" [data]="tablePresetData" [modes]="['compact', 'dashed']"></eds-table>
</div>

eds-table:

selector: 'eds-table',
template: "<table class=\"table\" [ngClass]=\"modes\">\n  <thead *ngIf=\"columns\">\n    <tr>\n      <th *ngFor=\"let col of columns\">\n        {{col.content}}\n      </th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr *ngFor=\"let row of data\">\n      <td *ngFor=\"let cell of row\">\n        {{cell.content}}\n      </td>\n    </tr>\n  </tbody>\n</table>\n",

If I want to add color based on different statuses, such as changing Busy text to green, Idle to Yellow, and Overload to Red, what should I do?

I appreciate your help.

Answer №1

Here is an example of how you can utilize the following code snippet:

<td *ngFor="let cell of row" 
  [ngStyle]="{'color': (cell.content === 'Busy') ? 'green' : (cell.content === 'overload') ? 'red' : (cell.content === 'idle') ? 'yellow' : ''}">{{cell.content}}
</td>

Make sure to apply the condition on cell.content, not row.content.

Answer №2

To create dynamic styling based on data conditions, utilize ngClass when building the table rows:

<table class="table\" [ngClass]="modes\">
    <thead *ngIf="columns\">
        <tr>
            <th *ngFor="let col of columns"> {{col.content}} </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let row of data">
            <td [ngClass]="{
                'busy' : cell.content == 'Busy',
                'idle' : cell.content == 'Idle'
                'overload' : cell.content == 'Overload'
             }" *ngFor="let cell of row"> {{cell.content}} </td>
        </tr>
    </tbody>
</table>

Add corresponding CSS to style the elements as needed:

.busy {
    background-color: green;
}

.idle {
    background-color: yellow;
}

.overload {
    background-color: red;
}

Answer №3

<table class="table" [ngClass]="modes">
    <thead *ngIf="columns">
        <tr>
            <th *ngFor="let col of columns"> {{col.content}} </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let row of data">
            <td [ngClass]="cell.content.toLowerCase()" *ngFor="let cell of row"> {{cell.content}} </td>
        </tr>
    </tbody>
</table>

Create a unique class for each type of status in the CSS:

.busy {
  color: red;
  /* Add any other desired css properties */
}

.idle {
  color: blue;
  /* Add any other desired css properties */
}

.overload {
  color: green;
  /* Add any other desired css properties */
}

View the code in action on StackBlitz. I have personally tested it and attached a screenshot below for reference: https://i.sstatic.net/o6sXM.png

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

Mini-navigation bar scrolling

I am trying to create a menu where I want to hide elements if the length of either class a or class b is larger than the entire container. I want to achieve a similar effect to what Facebook has. How can I make this happen? I have thought about one approac ...

Is it possible for the Chrome mobile camera to take up the full screen size on

Currently, I am using the code below to access the camera and display the stream. The width of the element is 100%, but the height seems to be around 70%. Is there a better way to make it fill the entire screen? HTML <video autoplay class="screen"> ...

Getting the Most Out of .find() in Angular 4

Despite reading various similar questions, I'm still struggling to make the .find() function work in my application. I have a service with the following API: export class VehicleService { private defUrl = 'API'; constructor(private ht ...

Update the Angular component once new data is saved in a separate Angular component

I've been diving into the world of MEAN stack and Angular, tackling a method within an angular component called itemListDetailsComponent (found in the .ts file) that looks something like this: onStatusUpdateClick() { this.activatedRoute.queryPar ...

Could the repeated utilization of BehaviorSubject within Angular services indicate a cause for concern?

While developing an Angular application, I've noticed a recurring pattern in my code structure: @Injectable(...) export class WidgetRegsitryService { private readonly _widgets: BehaviorSubject<Widget[]> = new BehaviorSubject([]); public get ...

I designed a dropdown menu with a searchable <mat-select> feature, where selecting an item is automatic when a space bar is pressed in the search box

Description : I have implemented a dropdown list using element that contains a list of items along with a search field. This allows users to easily search for specific items in the list instead of manually scrolling through a long dropdown menu. They can ...

The fine balance between a horizontal <img> and a <div> element

Can't seem to get rid of the thin white line between a black image and a div with a black background on a page where the body background is set to white. I've tried setting border: 0 !important among other things, but it just won't go away. ...

Fixing issues with internal web page connections (#x) present in the HTML code (href="#x" id="x")

Can anyone come up with a brilliant solution as to why my internal links are not functioning properly on a webpage? I've coded the HTML with the usual <a href="#link"><button>Some Text</button></a> .... bunch of content .... & ...

The designated apiUser.json file could not be located within the _http.get() function

It's puzzling why my URL isn't working in _http.get('app/api/apiUsers') for Angular version 4.0.0, when it functions correctly in Angular version 2.3.1. The code is identical in both Angular versions: import { Injectable } from ' ...

Updating color of an element in SVG and Angular2+ according to the background

In my svg element, I have a text element positioned after two rect elements. <svg id="floor-plan" width="300" height="100"> <rect width="300" height="100" fill="white"/> <rect width="50" height="50" fill="green"/> <text x="10" y="10" ...

Locate and refine the pipeline for converting all elements of an array into JSON format using Angular 2

I am currently working on implementing a search functionality using a custom pipe in Angular. The goal is to be able to search through all strings or columns in a received JSON or array of objects and update the table accordingly. Here is the code snippet ...

ngc encountering issues when compiling project with untyped third-party libraries

Utilizing a third-party library without defined types, the project is being developed using Angular CLI (version 1.0.0-beta.29) and the library is declared in typings.d.ts. In this instance: declare module ‘xml2js-es6-promise’; The project compiles an ...

How to create a slideToggle effect for nested ul and li elements

Initially, everything was working fine until I put it through the W3C validator. After fixing the errors, now it's not functioning as expected. I have created a jsfiddle The setup involves nested ul elements being used as dropdowns, with headers tha ...

Formulate a jQuery array consisting of droppable components

I have successfully implemented draggable li-elements and droppable boxes using jQuery UI. Here is my structure: A list of 3 different permission types <ul> <li data-action="create">Create</li> <li data-action="edit">Edi ...

One way to automatically create unique reference numbers is to generate a random number between 1 and 99 and append it to a date format, such as YYMMDD. For example,

I have a code that generates numbers like 030317-001 to 030317-010 in a list. How can I modify it so that the same sequence is generated with just one button click, without any repeats, up to a maximum of say 030317-099? <?php $x = date("dmy");// ...

The onClick event in ReactJs appears to be ineffective when used with a button HTML element

Can someone help me troubleshoot this issue in my ReactJs app? import React from 'react' import '../../../assets/styles/authentication/login.css' import '../../../assets/bootstrap/css/bootstrap.min.css' import { login } fro ...

Adjusting text size in iOS7 when converting HTML to NSAttributedString

My UITextView is currently handling an NSAttributedString that was initially entered using the keyboard. I save this attributed string as HTML, and it looks fine. However, when I load it again and convert it back to an attributed string from the HTML, the ...

I'm having trouble adjusting the background color in the bootstrap template

------------ I am customizing the bootstrap SB Admin template for my asp.net core Identity project. However, I am facing an issue with changing the background color of the template and the navigation menu color. Even though I can see the color changes when ...

Utilize jQuery to alter the presentation in a distinct field

Whenever a checkbox is clicked, it updates a display field. I want to capture the content of this display field and also show it in another display field. Ideally, the second field, which is a total field, would add or subtract the value from the first fie ...

Use CSS and JavaScript to create a visually appealing and interactive tree structure. Give the tree a dynamic design

I have been experimenting with CSS and JavaScript to create a dynamic graph based on a data table. You can view the graph that I need to replicate using CSS and JavaScript in this PDF. The example provided below showcases what I am attempting to achieve, a ...