Using an Angular pipe, you can dynamically adjust the background color based on the data

In my HTML, I am using a div with an *ngFor loop to iterate through userList:

<div  *ngFor="let user of userList">
    <div>{{ Name }} </div>
</div>

Also, I have an object containing codes and colors:

 [
        {
            "code": "A",
            "color": "#0071e3"
        },
        {
            "code": "B",
            "color": "#ff0000"
        },
        {
            "code": "C",
            "color": "#249309"
        },
    ..
    ]

The task is to match the starting letter of each Name in the userList with the code in the object and assign the corresponding color.

Answer №1

Your HTML code should look like this:

<div *ngFor="let user of userList">
  <div [style.color]="user.Name | firstLetterBg">{{ user.Name }}</div>
</div>

Here is the pipe code:

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

@Pipe({
  name: 'firstLetterBg'
})
export class FirstLetterBgPipe implements PipeTransform {

private colors: Array<{code: string, color: string}> = [
    {
      "code": "A",
      "color": "#0071e3"
    },
    {
      "code": "B",
      "color": "#ff0000"
    },
    {
      "code": "C",
      "color": "#249309"
    }
];

  transform(name: string): string {
    const firstLetter = name[0].toUpperCase();
    const colorObject = colors.find(x => x.code === firstLetter);
    return colorObject ? colorObject.color : '';
  }
}

@MatthieuRiegler suggests using a directive instead. You can modify my code to achieve that.

Best regards,

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

Steps to reveal a concealed div when a button is pressed and hide the button in Angular 2

Having trouble with Angular UI development, particularly with the following requirement: When the Add Button is clicked, a hidden form should be displayed. Clicking the Add Button should also hide it. The hidden form includes a Cancel button. If Cancel i ...

Laravel 5.7 not receiving form data when submitted from Angular 7

I am currently working with Angular 7 and Laravel 5.7. My objective is to send data from Angular to Laravel. Below is the snippet of my Angular 7 code responsible for posting data to the Laravel API: const target = event.target; const name = targ ...

Using Angular's router-outlet can sometimes result in replacing or updating the

I'm currently working on a larger application that has many reusable parts which aren't truly reusable yet. My idea is to develop a module specifically for dialogue windows, which will determine the type of dialog window to display and overlay it ...

Is it possible to deactivate input elements within a TypeScript file?

Is it possible to disable an HTML input element using a condition specified in a TS file? ...

I noticed that when using Next.js with the `revalidate: 1` option on a static page, it is triggering two full F5 refresh actions instead of just one. I was hoping for

Currently, I have set up a blog post edit page in my Next.js project. The post pages are utilizing the Incremental Static Regeneration feature with a revalidation time of 1 second for testing purposes. In the future, I plan to increase this to a revalidat ...

Using Firebase collection inside an Angular constant

Currently, I am working on a Datatable using ng-bootstrap that utilizes a static array to display data. There are 3 main files involved: In the "country.ts" file, the necessary values are declared: export interface Country { id: number; name: string; ...

Deactivate the rows within an Office UI Fabric React DetailsList

I've been attempting to selectively disable mouse click events on specific rows within an OUIF DetailsList, but I'm facing some challenges. I initially tried overriding the onRenderRow function and setting CheckboxVisibility to none, but the row ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

I encountered the error message "The property you are trying to access does not exist on the type 'never'" while attempting to retrieve JSON data from the API response

Every time I attempt to access the fields in items such as id or title, an error pops up saying Property does not exist on type 'never'. Interestingly, when I log the data using console.log(response.data), everything seems to be working fine. I ...

Nestjs: Step-by-step guide to removing a specific application from a Nestjs monorepo using nest/cli

Is there a method to delete a specific app within a nestjs monorepo using the nest/cli? I have searched through the documentation and developer forums but cannot seem to find a solution. ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

Tips for transforming promise function into rxjs Observables in Angular 10

As a beginner in typescript and angular, I am trying to understand observables. My query is related to a method that fetches the favicon of a given URL. How can I modify this method to use observables instead of promises? getFavIcon(url: string): Observ ...

Type guards do not work properly on a union of enum types in TypeScript

Recently delved into the concept of Type Guards Chapter within the realm of Typescript However, I encountered an issue where my basic type guards failed to differentiate a union of enums. Why is this happening? enum A { COMMA = ',', PLUS = & ...

Creating a personalized bullet text box with HTML and Javascript: A step-by-step guide

I have been working on creating a customized text box using HTML and JavaScript that has specific requirements: The text box should start with a single bullet point, like this: https://i.sstatic.net/U7pHo.png Each new line entered by the user should autom ...

Even when I try to access the properties of the arguments object, it remains empty and has a zero

Why is the arguments object showing a length of zero when I pass parameters to the function, even though I can still access its properties? I am referring to the arguments object that is implemented by all JavaScript functions, allowing you to access the f ...

How can the adapter pattern be implemented in Angular when dealing with an HTTP response containing an array of objects?

Using the adapter pattern in Angular, I have successfully adapted Http response to an 'Invoice' object. However, I am facing a challenge when one of the properties inside the 'Item' is an array. In this scenario, the 'items' ...

Is it possible for input properties of array type to change on multiple components in Angular 9?

Encountering an interesting issue that I need clarification on. Recently, I developed a compact Angular application to demonstrate the problem at hand. The puzzling situation arises when passing an Array (any[] or Object[]) as an @Input property to a chil ...

Creating a custom colored progress bar in Angular 2 using Bootstrap 4

I've been working on implementing a bootstrap progress bar with ng-bootstrap components. The documentation outlines 4 preset coloring options using the directive "type": "success", "info", "warning", or "danger". () To customize the colors, I made ad ...

React component's state is not being correctly refreshed on key events

Currently facing an issue that's puzzling me. While creating a Wordle replica, I've noticed that the state updates correctly on some occasions but not on others. I'm struggling to pinpoint the exact reason behind this discrepancy. Included ...

What is the best way to free up memory after receiving responseText in a continuous streaming request?

Utilizing xmlHTTPRequest to fetch data from a continuous motion JPEG data stream involves an interesting trick where responseText can populate data even before the request is completed, since it will never actually finish. However, I have encountered some ...