Is there a more effective alternative to using the ternary condition operator for extended periods of time?

Do you know of a more efficient solution to handle a situation like this?

<tr [style.background]="level == 'ALARM' ? 'violet' : level == 'ERROR' ? 'orange' : level == 'WARNING' ? 'yellow' : 'white'">

If I had 10 levels, it would become hard to read.

Answer №1

In order to access various colors, you can store values in an object and retrieve them using specific key properties

compoment.ts

colorMap = {
'ALARM': 'violet',
'ERROR': 'orange',
'WARNING': 'yellow',
'DEFAULT': 'white'
}

component.html

<tr [style.background]="colorMap[level]">

Answer №2

To solve this problem, a simple pipe can be used

@Pipe({
  name: "mypipe",
  pure: true
})
export class MyPipe implements PipeTransform {
  public transform(level: string): string {
    return level == 'ALARM' ? 
    'violet' : level == 'ERROR' ?
    'orange' : level == 'WARNING' ?
    'yellow' : 'white';
  }
}

How to use:

<tr [style.background]="level | mypipe">

Answer №3

Custom pipe for color coding:

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

@Pipe({
    name: 'levelPipe'
})
export class LevelPipe implements PipeTransform {

    transform(value: any, args?: any): any {
        return LevelsMap[value];
    }
}

export const LevelsMap = {
  ALARM: 'violet',
  ERROR: 'orange',
  WARNING: 'yellow',
  OTHER: 'white'
};

How to use:

<div [style.background]="level | levelPipe">Example</div>

View the live demo here: Demo app

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

Module for migration located in a subdirectory

Currently, I am in the process of transitioning an Angular application to NativeScript while utilizing a code-sharing setup. For the migration of Angular modules, I have been executing the following command: ng g migrate-module --name=nameModule However ...

The Angular form remains invalid despite all form fields being valid

After spending hours on an Angular form validation project, I have encountered an issue that has been difficult to resolve. The form I created seems to be working fine based on a demo I shared, where it shows the form status as VALID. However, when running ...

Guide to creating jest unit test for an observable variable exclusively utilized in a template resulting in the error "Property 'pipe' of undefined cannot be read"

Seeking help with creating unit tests for an Angular component that utilizes a constructor and observable variable in the HTML template. Below is the code snippet I am having issues with: voice-summary.component.ts export class VoiceSummaryComponent { v ...

Tips on formatting the date model field in an Angular 2 form

I have a model with a date field in MySQL format "yyyy-mm-dd hh:ii:ss" When displaying this field in my form, I want to show it in an input with a custom format: "dd/mm/yyyy" <input [(ngModel)]="model.date" name="date" view-format="DD/MM/YYYY" model-f ...

Struggling to locate the module in React Native with TypeScript configuration

Currently, I am in the middle of transitioning our react-native project from JavaScript to TypeScript. As I attempt to import old modules, I keep encountering the following error: Cannot find module 'numeral' Oddly enough, the 'numeral&apo ...

Encountering npm3 installation errors with typyings in Angular 2?

Each time I try to sudo npm install Angular 2 modules, everything updates and installs correctly. However, I encounter the following error when the typings install is attempted: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0 ...

When implementing useReducer with TypeScript, the error "Argument of type '(type, action) => { state: (...}' is not assignable to parameter of type 'ReducerWithoutAction<any>'" may occur

Recently, I decided to delve into learning TypeScript by building a simple shopping cart application. If you want to check out the code, feel free to visit my GitHub repository: https://github.com/CsarGomez/shopping-cart-reducers-tx I've encountered ...

Angular 2 is having trouble with object dot notation in Typescript and is expecting a semicolon

Hello, I am currently transitioning a project from Angular 1 to TypeScript and Angular 2. One issue I'm facing is getting some property definitions into the Angular 2 component. Below are the property definitions causing trouble: import { Component ...

The Typescript generics are unable to be assigned to type T

Take a look at my code snippet: interface IDoc { doSomething(): void } class IDocFoo implements IDoc { doSomething(): void { console.log('Do doSomething'); } } class IDocFactory { getIDocInstance<T extends IDoc>(): T { re ...

Is it possible to use jQuery to set a value for a form control within an Angular component?

I'm currently working on an Angular 5 UI project. In one of my component templates, I have a text area where I'm attempting to set a value from the component.ts file using jQuery. However, for some reason, it's not working. Any suggestions o ...

Exploring how process.argv in NodeJS can be utilized within JavaScript code compiled by

I'm having trouble compiling a basic TypeScript file using webpack (with 'awesome-typescript-loader') that needs to access command line arguments. It seems like the compiled JavaScript is causing a problem by overriding the Node 'proce ...

Issue with running "ng generate" or "ng add" commands

While using angular version 8 in Termux Android ARM, I encountered an issue when trying to add the PWA and service worker to my website project. Here is the information about the angular version obtained from Angular CLI: $ ng version _ ...

Using react-confetti to create numerous confetti effects simultaneously on a single webpage

I'm looking to showcase multiple confetti effects using the react-confetti library on a single page. However, every attempt to do so in my component seems to only display the confetti effect on the last element, rather than all of them. The canvas fo ...

Is it necessary for me to individually download every x.d.ts file for my application?

Do I need to include the following line for type checking when using fs.readFile in TypeScript? /// <reference path="node.d.ts" /> Is it considered 'best practice' to download and maintain the most recent version of node.d.ts file in my ...

What is the best way to transform an Observable<Observable<HttpEvent<any>>> into an Observable<HttpEvent<any>> within the Angular AuthInterceptor service?

export class AuthInterceptor implements HttpInterceptor { constructor(private usersService: UsersService){} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return this.usersService ...

Using Typescript to configure a custom proxy in a Create React App

I am looking to implement request proxying from a Create React App to a separate API server, with the ability to set the server dynamically or using environment variables. While I have followed the guide on manually configuring the proxy, I am encounteri ...

"Utilizing TypeScript Definitions in a Node.js/Express Application: A Step-by-Step

I initially started using tsd and typings to install declaration files from external sources and reference them in the server file. However, now we have the option to obtain declaration files through @types/filename. I'm not sure why the move was made ...

The tooltip is obscured by the table row

I'm having trouble with a simple CSS fix and can't seem to figure out why. The z-index and overflow visibility properties are not working as expected. I just need 'In Progress' to be displayed above everything else. Some things I' ...

Exploring the integration of an Angular 4 application with Visual Studio 2017 using dot net core. Techniques for accessing configuration keys from appsetting.json in a TypeScript

I'm currently working on an Angular 4 application using Visual Studio 2017 with .NET Core. I need to figure out how to access configuration keys from appsetting.json in my TypeScript file. I know how to do it in the startup.cs file, but I'm strug ...

What is the best way to guarantee that an object contains certain fields using Partial<>?

I am dealing with a function that accepts a parameter as shown below: const handleAccount = ( account: Partial<IAccountDocument>, ... ) => { ... } It is crucial that the interface for IAccountDocument cannot be modified to avoid requiring cer ...