Adjust the color of the icon depending on the value

I am new to Angular2 and I'm looking for a way to dynamically change the CSS of an icon based on specific values.

Here is the code in HTML:

<li><i class="fa fa-check" [style.color]="'switch(types)'"></i>{{ types }}</li>

values assigned to 'types' range from 1 to 3.

In TypeScript:

switch(p) {
    if(p == 0) {...} //set color to red
    if(p == 1) {...} //set color to blue
    if(p == 2) {...} //set color to green
}

However, this method doesn't seem to be effective for me.

Answer №1

Implementing a switch statement within the body is currently missing in the code. Another approach could be to utilize function binding, although not the preferred method. Unfortunately, no other solution has been identified yet.

[style.color]="color(types)"


color(p) {
    if(p==0) {return 'green'} 
    if(p==1) {return 'red'} 
    if(p==2) {return 'blue'} 
}

View the DEMO here : https://plnkr.co/edit/zQ79mbS2U3X1s9ktnTIR?p=preview

Answer №2

   <ul>
        <i class="fa fa-check-circle" [ngStyle]="{'color': updateColor(types)}"> 
            {{types}}
        </i>   
   </ul>


updateColor(p) {
    if(p==0) {return 'purple'} 
    if(p==1) {return 'orange'} 
    if(p==2) {return 'yellow'} 
}

Answer №3

Another way to tackle this problem is by incorporating the conditions directly within the [ngClass] attribute. Here's how you can do it:

[ngClass]="{'red':types === 0,
  'blue':types === 1,
  'green':types === 2}"

This method works well for a small set of values because each condition is independent. Don't forget to define these new classes in your CSS file as well.

.red{
   color:red;
    }
.green{
   color:green;
 }
.blue{
   color:blue;
 }

By using this approach, you can avoid the extra overhead of calling a method every time the layout needs to be recalculated at run time. This solution would be ideal for simpler scenarios like the one you've described. However, for more complex criteria or a larger range of values, utilizing a function call might be a better choice.

Answer №4

Here is an example of how you can achieve this:

<li><i class="fa fa-check" [ngStyle]="applyStyles(types)"></i>{{ types }}</li>

      applyStyles(types:any){
    let dynamicStyles: any;
      if(types == 0){
        dynamicStyles = {
          'background':'..',
          'border-color':'....',
          'border-bottom': '...',

        }
    }
return dynamicStyles;
}

I hope this explanation helps

EDIT: I have followed the suggestion to remove the ''

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

Leveraging Expose in combination with class-transformer

I have a simple objective in mind: I need to convert the name of one property on my response DTO. refund-order.response.dto.ts export class RefundOrderResponseDto { @Expose({ name: 'order_reference' }) orderReference: string; } What I w ...

Components will be displayed without any gaps on smaller screens

I attempted to apply styles to two components in order to create space between them, visible on both larger and smaller displays. The code snippet appears as follows: <div> <CustomPageHeader pageTitle={t('offersPage.pageHeader')} ...

Place the setState function within the useEffect hook

I'm currently working on a project that includes a "login" page. Once the user logs in, they should be directed to an interface displaying all their lists. To ensure this data loads immediately after login, I have implemented the useEffect hook and u ...

The process of altering the color of a table row in JavaScript can be done after dismissing a pop-up that was triggered by a button within the same row

I am tasked with changing the color of a specific table row based on user interaction. The table consists of multiple rows, each containing a button or image. When the user clicks on one of these buttons or images, a popup appears. Upon successful data sub ...

What is the best way to eliminate the extra spacing on the right side of my navigation bar?

Hello everyone! I am diving into the world of HTML and CSS, but I've hit a roadblock. Despite searching through various resources and forums, I can't seem to find a solution to my problem. The issue at hand involves an irritating space in my nav ...

Exploring ways to destructure the useContext hook with a null default value in your Typescript code

Initially, I set up a context with a null value and now I am trying to access it in another component. However, when I destructure it to retrieve the variables from the context, I encounter a TypeScript error: Property 'users' does not exist on ...

Sending information from ngRoute resolve to the controller

I am currently working on an application that utilizes ngRoute to create a Single Page Application. One of the requirements is to ensure that the view is not loaded until the data has been successfully fetched from the database. While I have managed to ach ...

The start-up process of AngularJS applications with Bootstrap

Curious about the predictability of the initialization flow in AngularJS apps? Want to understand the order of execution of different blocks within an HTML document? I came across a question on bootstrapping in Angular JS, but it didn't delve into th ...

What is the method for incorporating a link in an accordion header next to the toggle button with Bootstrap?

I'm attempting to enhance a link in the accordion-button so that only the arrow is clickable for collapsing. The CSS I added below makes the arrow clickable, but I am having trouble getting the link in the accordian-button to work. I want users to be ...

Using jQuery's ajax to populate several div elements in a single call

Trying to wrap my head around jQuery's Ajax function. There exists a page composed of various divs, along with an XML document generated from a MySql resultset. Within the jQuery function displayed below, I successfully fill the titleDiv with data. M ...

How to extract JSON data from an HTTP request in Java

I'm seeking to scrape data from a specific link using a Java program. The initial page is not an issue, but when attempting to gather data from subsequent pages, the source code remains the same as on the first page. The vital information I require is ...

When working with React and Typescript, I encountered an issue with refs causing a typescript error: "The property 'current' does not exist on the type '(instance: HTMLInputElement | null) => void'"

I am working on a component that requires a ref prop: import React, {forwardRef, ReactElement, ReactNode, HTMLProps, useRef} from 'react' import styles from './index.module.css' import classNames from 'classnames' import { Ico ...

Retrieve data using Angular FileReader's onloadend method and return the result

When working with audio recording in Angular, I encountered a challenge with my code. The goal was to record audio, obtain the blob, and convert it to base64 using FileReader. However, I struggled with returning this base64 data from the onloadend method o ...

Adding CSS code to my index.css file in React is not reflected in my application

I've been following a tutorial on YouTube about reactJS, and the YouTuber recommended importing a CSS file into index.css to properly style the website. However, when I tried copying the CSS code and importing it into both App.js and Index.js, nothing ...

Ensuring the footer stays anchored at the bottom using Material-UI Expansion Drawers

Utilizing Material-UI@next in my React application, I have a component that showcases a list of items using Expansion Panels. Additionally, there is a straightforward <Footer /> component structured like this: import React, { Component } from "react ...

Exploring Angular 5 Localization

I am new to the concept of locales. I recently created an Angular 4 app that reads the locale from the browser using the navigator.language() API and provides it to Angular's pipes. However, with the changes in v5, I have some questions regarding migr ...

In Typescript, you can easily group a string into sections that consist of digits like 345-67, along with text containing a

I have a string that looks like this: "[111-11] text here with digits 111, [222-22-22]; 333-33 text here" and I am trying to parse it so that I can extract the code [111-11], [222-22-22], [333-33] along with their respective text descriptions. The challeng ...

Combine multiple objects to create a new object that represents the intersection of all properties

Imagine you have these three objects: const obj = { name: 'bob', }; const obj2 = { foo: 'bar', }; const obj3 = { fizz: 'buzz', }; A simple merge function has been written to combine these three objects into one: ...

Utilizing Jquery to automatically scroll to a specific div on page load by setting an

I am attempting to automatically scroll to the div specified in the URL. The URL may include one of 21 different IDs such as: url.com/test#lite1 url.com/test#lite2 url.com/test#lite3 This scrolling action should happen when the page loads (so that user ...

Implement a click event using jQuery specifically for Internet Explorer version 7

How can I add an onclick attribute using jQuery that is compatible with IE7? So far, the following code works in browsers other than IE8 and Mozilla: idLink = Removelst(); var newClick = new Function(idLink); $(test1).attr('onclick', null).clic ...