I have this Angular component where hover effect is currently applied with pseudo-class :hover
in .scss file. But I want to apply the hover effect with dynamic values.
So suppose if I want the element’s background to change on hover, the current css looks like this:
.element { display: flex; justify-content: center; &:hover { background-color: red; } }
But now I want the hover background color to have dynamic values that is available inside the component provided by the user from the UI so the color could be anything. Another thing which I also want to achieve is to add a class to the element when it is selected. What I mean is when hovered, the background will change to a dynamic value but if the element is selected, that same color will be the background color. And if unselected, it will go back to the original color.
I’m new to Angular so I’m not sure how to achieve this. Anyone can help me?
Advertisement
Answer
You cannot dynamically set pseudo classes via JavaScript. You would have to either:
- Implement your own dynamic styling using the mouseover event in your component
- Swap to a pure CSS solution and let the consumer of your component override the hover pseudo selector with the desired color in their own CSS.
I would favor the second option. Turn off view encapsulation in your component declaration, make sure your component CSS is reasonably contained to just that component via some CSS component methodology like BEM, and just let the consumer override your styles.