What is the process for extracting the background color from a typescript file in Angular and connecting it to my HTML document?

My typescript array population is not changing the background color of my div based on the values in the array. I've attempted to set the background using [style.backgroundColor]="statusColor[i]", where statusColor is an array declared in my typescript. This approach fails, unlike binding without an array to a single object as shown: [style.backgroundColor]="statusColor". The error message says: "Cannot read property '0' of undefined".

Below is the mentioned code:

export interface IComplaint {
    id: string;
    description: string
    status: string
}
public complaints = {} as IComplaint[];        
public statusColor: string[];

for (let i=0; i<this.complaints.length; i++) {
        if (this.complaints[i].status === "Reported")
          this.statusColor[i] = 'red';
        else if (this.complaints[i].status === "Resolved")
          this.statusColor[i] = 'green';
        else if (this.complaints[i].status === "In progress")
          this.statusColor[i] = 'yellow';
        console.log(this.statusColor[i]);
}       

This is how the HTML code looks like:

<mat-card class="card" *ngFor="let complaint of complaints; let i = index">
<div class="status" [style.backgroundColor]="statusColor[i]">
                        {{ complaint.status }}
                </div>
</mat-card>

<div class="status" [style.backgroundColor]="statusColor[i]">
                            {{ complaint.status }}
                    </div>  

The goal is for the background color to change according to the status.

Answer №1

You can utilize ngStyle in the following manner

[ngStyle]="{'color': highlightColor[i]}

Answer №2

Consider using this style binding instead:

[style.background-color]="statusColor[i]"

To enhance your code, I recommend implementing a pipe for processing. Pipes are also optimized for performance.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'complaintBgColourPipe'
})
export class ComplaintBgColourPipe implements PipeTransform {
  transform(value: string): string {
    switch (value) {
      case 'Reported': {
        return 'red';
      }

      case 'Resolved': {
        return 'green';
      }

      case 'In progress': {
        return 'yellow';
      }

      default: {
        return '';
      }
    }
  }
}

Instead of manually handling each status in your complaints array, you can simply pass the status to the pipe for processing.

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

Incorporating map, forkJoin, and mergeMap into your code base can

I have a requirement to perform multiple API calls. The first API call returns a list of objects with the properties userId and propertyId. For each item in this list, I need to fetch additional information called userInfo and propertyInfo based on the I ...

What is the best way to breakdown the MVC pattern within Angular 2?

Discovered a useful blog about Angular: MVC Implementation, but interested in finding a clear explanation for Angular 2. ...

Toggle multiple buttons based on the data fetched in the created() lifecycle hook

I have several toggle buttons that should be selected based on the values present in the response obtained through the created() method. <li> <input v-on:click="toggleCheckbox($event)" ...

Replace old content with new content by removing or hiding the outdated information

I need to update the displayed content when a new link is clicked index html file <a href="" class="content-board" > <a href="" class="content-listing" > content html file <div class="content-board"> <div class="content-lis ...

Issue with FusionCharts rendering correctly arises when the <base> tag is present in the HTML head section

Combining AngularJS and FusionCharts in my web application has led to a unique issue. The upcoming release of AngularJS v1.3.0 will require the presence of a <base> tag in the HTML head to resolve all relative links, regardless of the app's loca ...

Tips on aligning data received as a response from a Perl script

Currently, I am utilizing a Jquery-Ajax call to a perl script in order to retrieve specific data. The perl script executes a database query and transmits the data back to the HTML page. while (my @data = $statement->fetchrow_array()) { print "$ ...

Incorporating an additional ion-item alongside the existing one instead of substituting it

I am retrieving a list of questions from an API with pagination. I have a button that triggers a function to load the next page of questions. Instead of replacing the previous page, I want to append the new questions below the existing ones. Here is my cur ...

The user interface in Angular 7 does not reflect the updated values after subscribing

Upon examining the code provided, it is evident that the UI does not reflect the updated value even though the field is set correctly. I have attempted two different approaches but have not explored the change detection approach as I believe the current c ...

The symbol 'router-outlet' is not recognized by the system

This new project utilizes Angular 13 for its implementation. One of the key updates is the addition of routing to the project, specifically in the file app-routing.module.ts. import { NgModule } from '@angular/core'; import {RouterModule, Routes ...

Div sliding out of view

I'm encountering a slight issue with this template: essentially, my goal is to implement a feature where clicking on a box will expand it while simultaneously sliding the other boxes off-screen. However, instead of just sliding the div off-screen, it ...

Why don't media queries take effect

After thoroughly reading all the @media topics on this site, it appears that the code should be functioning correctly. body { background-color: yellow; } @media screen and (min-width: 1080px;) and (max-width: 2000px;) { body { backgrou ...

What is the best way to personalize the icon for this navigation button?

I'm interested in making some changes, especially to the border. I've already figured out how to adjust the color of the 3 bars like so: .navbar-default .navbar-toggle .icon-bar { background-color: #fff; } Modification RESOLUTION .navbar- ...

There seems to be a bug in the reducer within the store (using react, redux toolkit, and TypeScript)

Utilizing redux with typescript, I aim to create a reducer that will modify the state of the store, and my defined types are as follows: interface IArticle { id: number, title: string, body: string, } type ArticleState = { articles: IArticle[] } ...

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

In Firefox, the CSS height and width values are displayed as X pixels, whereas in Internet Explorer, they are automatically set to 'auto'

When it comes to measuring div box dimensions, jQuery can be a handy tool. Here is an example code snippet: $(document).ready(function(){ var h = $("#testbox").css("height"); }); Interestingly, the same code can give different results in different brow ...

NodeJS instructs open(html) to execute first before any other code is executed

I am evaluating whether nodeJS is a suitable solution for a project I am working on during my internship. To summarize: I need the basicNode.js file to wait until the open('./basic.html') command has completely opened the browser and loaded its c ...

Enhancing code completion with IntelliSense for customized styled components' themes

When using a theme in styled components, I am attempting to enable IntelliSense. In my code snippet below (index.tsx), I utilize ThemeProvider: import React from 'react'; import ReactDOM from 'react-dom/client'; import { ThemeProvider } ...

I have tried using justify-content: center; and align-items: center; to center this div, but the container div is still not centered. How can I successfully center

I am having trouble centering the container in my HTML code HTML code:- <body> <div class="container"> <div class="image"> <img src="./images/image-qr-code.png" alt="qrcode"> & ...

Switch Button Hyperlink in HTML/CSS

I have the following code: document.addEventListener("DOMContentLoaded", function(event) { (function() { requestAnimationFrame(function() { var banner; banner = document.querySelector('.exponea-banner3'); banner.classList ...

Transforming global CSS into CSS modules: A step-by-step guide

In my nextjs project, I am utilizing react-bootstrap and bootstrap which requires me to include the global css: // _app.js import 'bootstrap/dist/css/bootstrap.min.css'; The issue arises when loading a significant amount of unused css on every p ...