Effective Ways to Transfer Data from Angular to CSS in an HTML Table

I am working on an Angular web app that includes an HTML table. The data for this table is retrieved from a database via a service and displayed as text.

One of the columns in the table represents a Status, which I want to visually represent as a colored circle instead of plain text. For example, if the cell value is "green", it should display a green circle.

Below is my current approach:

CSS (Component Styles snippet):

:host ::ng-deep td.circle { 
  text-align: center;
  font-size: 0;
  background-color: RED;  <---  need to pass param here
}

The column styling is defined as follows:

.circle {
  border-radius: 50%;
  height: 24px;
  width: 24px;
}

HTML:

<app-table [attrs]="serviceapi" [monthSelected]="monthSelected" ></app-table>

Corresponding TypeScript code for the table: In the constructor:

this.data =  {
  headers: [],
  rows: []
};

ngOnInit() {
  this.tableMetricsService.getTableMetrics(
     JSON.parse(this.attrs).api,
     this.monthSelected
  ).subscribe(response => {
    this.data = response;
    }
  );
}

Does anyone have suggestions for translating cell values into corresponding CSS background colors?

Thanks in advance,

Oleg.

Answer №1

This code snippet was successful for me:

<div *ngIf="cell.styleClass == 'circle'" [ngStyle]="{'background-color': cell.value}" [ngClass]="cell.styleClass">
              </div>

Answer №2

One option is to add a data attribute to the HTML and create a corresponding selector:

[data-status="green"] {
  background: green;
}

[data-status="red"] {
  background: red;
}
<div data-status="green">Green</div>
<div data-status="red">Red</div>

However, using a regular CSS class may be just as effective without the need for extra attributes:

.green {
  background: green;
}

.red {
  background: red;
}
  <div class="green">Green</div>
  <div class="red">Red</div>

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

I have integrated ng-bootstrap and ngbDatepicker for the calendar feature, and I am looking to automatically increase the end date by one day whenever I select a start date from the calendar

Currently, I am working with ngbDatepicker and I have a requirement to automatically add one day to the calendar when the user selects a start date. The start and end date variables are defined in the following format: public startDate: NgbDate; public ...

Limit the utilization of toString through a TypeScript interface or type

Here's the interface I'm aiming for: export interface Point { readonly x: number; readonly y: number; readonly toString: never; } I initially expected it to function this way: const p: Point = {x: 4, y: 5}; // This should work fine p.toStr ...

Is there a more efficient method for providing hooks to children in React when using TypeScript?

My component structure looks something like this: Modal ModalTitle ModalBody FormElements MySelect MyTextField MyCheckbox DisplayInfo ModalActions I have a state variable called formVars, and a function named handleAction, ...

Incorporating an external module into your Angular application for local use

I currently have two projects: my-components, which is an Angular library, and my-showcase, an Angular app. Whenever I make changes or add a new component to my library, I commit it to a private git repository and publish it to a private npm registry. This ...

How do I change the alignment of X axis labels in an Asp.net chart to be left-aligned instead of centered?

I've been struggling for hours trying to figure out this simple issue. I am working on creating a histogram using the asp chart control. My main problem is that I can't seem to get the x-axis label to appear on the left side of each column instea ...

Arranging pictures in both vertical and horizontal alignment (CSS)

I've been attempting various methods to solve this issue, but none have proven successful. My goal is quite simple: align images both horizontally and vertically in a manner that fills empty spaces with photos. Similar to the layout here: The challe ...

Best practice for saving a User object to the Request in a Nest.js middleware

Currently, in my nest.js application, I have implemented a middleware to authenticate Firebase tokens and map the user_id to my database. Within this middleware, I retrieve the user_id from Firebase, fetch the corresponding User object from the database, a ...

Utilizing Smarty Template: Combining <li> elements from separate <ul> tags for a seamless display

On my Prestashop website, I have implemented the "Advanced Homepage Product List" module. I removed the category names from the titles to have my items sorted without displaying the category names. Currently, this is how it appears: https://i.stack.imgur. ...

The rules for prioritizing CSS selectors

Struggling with CSS selector rules and specificity? I've already checked this for specifics. Even tried using firebug and inspecting elements in Chrome to copy the CSS path, but still can't get it to work. This is my first time creating a website ...

Incorporating Bootstrap into a fresh project

I'm completely new to the world of development, so I'll do my best to phrase this question correctly! Last month, I successfully created my first web application using RoR and Bootstrap for some visual enhancements. Currently, I am working on a ...

NestJS Resolver Problem: Getting an Undefined Error

Could use a bit of assistance. I'm currently working on a mutation and encountering the following error: ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'entryUser') Here is the resolver code snippet: export class Us ...

Ensure that the fixed element adheres to the overflow:hidden property

It's truly baffling that I can't figure this out! Is there a way to make a fixed element respect the overflow setting? I created a fiddle for reference - http://jsfiddle.net/REk4C/7/ In the fiddle and the image above, you'll notice a cont ...

The Typescript counterpart to PropTypes.oneOf, utilizing a pre-existing variable

While I know this question has been addressed on Stack Overflow here, I still find myself struggling with a similar issue in my TypeScript project. Currently, I am in the process of converting a JavaScript project to Typescript. Within one of my React com ...

Mastering the use of Quasar variables in your scss styles is crucial for optimizing your

I recently set up a project using Vue3 and Quasar by running vue add quasar. However, I am struggling to figure out how to utilize Quasar sass/scss variables. According to the documentation, I should use the following syntax: <style lang="scss&quo ...

Navigating between child nodes in an HTML drop down list with multiple options and hierarchical structure

Hey there! I am looking to create a unique HTML hierarchy drop-down menu. It will have multiple levels or options, with each option having the potential for child nodes. When an option has child nodes, an arrow will appear next to it. Clicking on this ar ...

Displaying a default input placeholder in Kendo UI Datepicker for Angular 2

I've recently implemented the [Datepicker feature from Telerik Kendo UI][1] While the datepicker functions perfectly, I have encountered a single issue where it displays undefined when the date value is not defined: [![enter image description here][ ...

Creating type definitions for recursive functions in TypeScript

I've created a JavaScript function that continuously accepts functions(params => string) until it receives an object, at which point it resolves the final string as a concatenation of all the functions invoked over the same object passed in at the ...

Instructions on uploading a PDF file from a Wordpress page and ensuring the file is stored in the wp-content upload directory folder

What is the process for uploading a PDF file on a WordPress page? <form action="" method="POST"> <input type="file" name="file-upload" id="file-upload" /> <?php $attachment_id = media_handle_upload('file-upload', $post->I ...

Imitate a Node.js Proxy

I am currently developing a Node.js/express application in typescript that involves a proxy route with specialized business logic for determining the proxy URL: import proxy from "http-proxy-middleware"; const controller = diContainer.get<IController& ...

What is the process for setting the active state for HtmlBodyElement?

I attempted to use the following method: document.querySelector('body').setActive(); However, I encountered an error: TS2339: Property 'setActive' does not exist on type 'HTMLBodyElement'. Any suggestions on how to resolve t ...