Change the background color of a span element dynamically

I am currently working on implementing dynamic background coloring for a span tag in my Angular view that displays document types. The code snippet provided is as follows:

<mat-card *ngFor="let record of records">
  <span class="doc-id">
    Document ID: {{ record.id }}
  </span>
  <span>
    {{ record.documentType }}
  </span>
</mat-card>

The record.documentType contains string values retrieved from the backend. The objective is to assign different random background colors based on the document type.

For instance:

If the documentType is 'employee', all employee documents should have a specific color (e.g., green). Similarly, if it is 'salary', salary documents should have another random color (e.g., yellow).

I have experimented with various solutions found online, but none have met my requirements adequately.

My current approach involves passing the documentType value to a TypeScript function, which will generate a new random color if one has not already been generated for that type.

[ngStyle]="generateRandomBackgroundColor(record.documentType)

Would you happen to have any suggestions or best practices for addressing this particular issue? I am utilizing Sass within the project, so any related suggestions are greatly appreciated.

Thank you in advance!

Answer №1

@Pipe({
  name: 'randomColor',
})
export class RandomColorPipe implements PipeTransform {
  private static readonly colors: Map<string, string> = new Map();

  /**
   * Generates random hex color
   * https://css-tricks.com/snippets/javascript/random-hex-color/
   */
  private getRandomColor(): string {
    return Math.floor(Math.random() * 16777215).toString(16);
  }

  public transform(id: string): string {
    const color = RandomColorPipe.colors.get(id) ?? this.getRandomColor();

    if (!RandomColorPipe.colors.has(id)) {
      RandomColorPipe.colors.set(id, color);
    }

    return color;
  }
}
<mat-card *ngFor="let item of items">
  <span class="product-id">
    Product ID: {{ item.id }}
  </span>
  <span [style.backgroundColor]="'#' + (item.category | randomColor)">
    {{ item.category }}
  </span>
</mat-card>

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 concealed [hidden] attribute in Angular2 triggers the display of the element after a brief delay

I am currently utilizing the [hidden] attribute within my application to conceal certain elements based on a specific condition. The situation is such that I have two divs - one for displaying results and another for showing the text "No results". Both t ...

Exploring a Firestore collection to extract data fields for storage and utilization

I'm currently facing a challenge while attempting to access my Firestore collection and iterate through all documents to extract the valenceId field in each document. Despite trying various approaches, I keep encountering an error message stating: "c ...

Utilize Angular 10 to send a post request and subsequently trigger another request upon successfully completing the first

I am looking for a way to register a user on the backend and then sign them in sequentially. The register route will create the user, while the sign-in route will return a UserModel object if successful. If registration fails, an error will be returned f ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

Implementing TypeScript in an Asp.net Core ReactJS application`s configuration

After using Visual Studio 2022 to create an asp.net core Reactjs project, I discovered that everything was written in javascript instead of typescript. Is there a way to switch this project over to typescript? ...

Updating the Angular2 function in the main app component causes the current component to be reset

I developed an application that has the following structure: app.component.ts import { Component } from 'angular2/core'; import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; import { NgClass } from &apos ...

Combine a constant interface with a generic function to create a unique generic interface

When dealing with legacy code that utilizes a const in the following pattern: const fnUsedInSetPrototypeOf = { equalityComparer<T>(a: T, b: T) { return a === b }, otherFn<T> (this: T) { /*...*/ }, // ... other things, all along the ...

Angular - Managing unexpected routes for customized functionality

I am in the process of creating an app with Angular 6 and I'm faced with handling unknown routes within my application. For instance: Instagram has a default page (instagram.com), but if you type in (instagram.com/user) it redirects you to the user ...

Using Angular to fetch API response and convert it into a promise

I've been following the Angular tutorial available at https://angular.io/tutorial/toh-pt6. The tutorial demonstrates how to retrieve a Json response from an API call and then match it to a promise. One specific example from the tutorial is as follows ...

Make sure to wait for the store to finish updating the data before accessing it. Utilize RxJS and Angular

Greetings! I am currently working with Angular and RxJS, and I'm trying to find a solution to wait for the store's data to be updated after an action is dispatched in order to perform some operations using that data. Below you can see a snippet o ...

Unusual Behavior of Observable.concat() in Angular 4 with RxJS 5

My Angular 4 / TypeScript 2.3 service has a method called build() that throws an error if a certain property is not initialized. I am attempting to create a safer alternative called safeBuild() that will return an Observable and wait for the property to be ...

Accessing class fields from within an annotation in Typescript

Upon using the code snippet below: @Component({ props: { value: String }, mounted() { //Do something with `bar` this.bar = this.bar + " is now mounted"; } }) export default class Foo extends Vue { priv ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

Element is missing the necessary "key" property. (React and TypeScript)

Upon running the following code for reactJS and typescript, I encountered the error below: I have also included the import statement import 'bootstrap/dist/css/bootstrap.min.css'; in Index.tsx. Is there a solution to resolve this issue? npm s ...

Troubleshooting the Angular 7 mat-select issue caused by the "ellipsis" CSS property with three dots

I am facing an issue with a mat-select property called "ellipsis". The three points appear in a different color than the text itself. I attempted to change it to white using the following code, but the dots still remain black. ::ngdeep .example{ ...

Exploring Angular: A Comparison of AfterViewInit() and AfterContentInit()

I am trying to understand exactly what triggers the AfterViewInit() and AfterContentInit() life-cycle hooks. According to the Angular documentation, AfterViewInit() is called by Angular after it creates a component's child views. and for AfterCon ...

How can you modify a button in Ionic 2 based on the login status, using a modal to redirect to a different page once authenticated?

I have a button on my main page that is supposed to display 'Log out' when the user is currently logged in, and 'Log in' when there is no active user session. Clicking on the login button opens a modal. After successful login, the user ...

Why isn't my Bootstrap affecting Angular?

Hello, I am currently working on a project using Angular. Recently, I installed Bootstrap and added it to angular.json, but unfortunately, the changes did not take effect even after restarting the app. Here is the code snippet that I am currently using: h ...

Display JSON Data in HTML using Ionic and Angular

I am currently in the process of developing an app using IONIC Angular, and I am facing a challenge with displaying the results in HTML. While I can successfully retrieve and display the data using console.log, I am encountering difficulties when trying t ...

Having trouble with Angular 5's Post function?

Having some trouble with my Angular 5 application and API calls. For some reason, when I add headers to the request, the browser is not recognizing them properly and showing 'OPTION' instead of the actual headers. This is resulting in a 403 respo ...