1

I have a function, which is returning me a background color from a json file list, getBackground(items). I am using one component which adds automaticly a class name upon each item click (its a list combo box component), it adds class .item-radio-checked. I want to find a way to set the background color via my function to this class, but I am not sure how, since this class is added only when user click over the item. I can use:

[style.background]="getBackground(items)"

but this applies to the background attribute of the item element, not to the class I want to trigger. Via css will not work, since its a static and I want the background color to be taken from my function. So it will be:

.item-radio-checked {
background-color: $colorname;
}

I know that i need to handle this via angular and over the DOM, not in the SCSS file, but I am not sure how.

I need to know each this is this class added to the item (has item been clicked) and apply the right dynamic color from my function to it

5
  • Check this answer Commented Dec 27, 2017 at 9:56
  • scotch.io/tutorials/the-many-ways-to-use-ngclass check this link. Commented Dec 27, 2017 at 10:10
  • Also agree, ngClass directive should work angular.io/api/common/NgClass Commented Dec 27, 2017 at 10:15
  • 1
    "I am using one component which adds automaticly a class name upon each item click (its a list combo box component), it adds class .item-radio-checked". I assume there's a property from that component that is used to add that class, right? Do you have access to that property from the view where you have the [style.background]="getBackground(items)"? If that the case, you can do something like this: [style.background]="conditionWhenClicked ? getBackground(items) : null" Commented Dec 27, 2017 at 10:28
  • Yep that one might work, with the condition. It's still sort of a tweaky because I am not sure which handler those component has for the click event, but I think I can trick it with my stuff. So this one is the answer I think so. Commented Dec 27, 2017 at 12:11

1 Answer 1

0

Use ngStyle:

<div [ngStyle]="{'background-color':getBackground(items)}"></<div>

Hope it will help.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think this one will work, since I want to apply the background color only when someone click over this item, or when the class has been added to it. So only elements which has this class, and has been clicked has this background set.
If you want to apply on click then just declare a string property in your component and use that property in ngStyle. On click change property value and rest Angular will take care.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.