1

I have a div and I want that when it is hovered the background color changes and I also need to choose the color based on an element in my component.

<div *ngFor="let u of users;" 
  [style:hover.background-color] = "u.selected ? 'red' : 'blue' ">
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
mszareian
  • 11
  • 2
  • See the answer here: https://stackoverflow.com/questions/35280118/change-style-of-pseudo-elements-in-angular2 – DeborahK Jul 11 '23 at 15:21

1 Answers1

0

From the above comment link:

"It is actually not an Angular issue: pseudo elements are not part of DOM tree, and because of that do not expose any DOM API that can be used to interact with them."

So you can instead use a CSS variable:

Style file:

.highlight:hover {
  background-color: var(--highlight-color);
}

Template:

    <div class="highlight" *ngFor="let u of users;" 
         [ngStyle] = "{'--highlight-color': u.selected ? 'red' : 'blue'} ">
      {{ u.name }}
    </div>
DeborahK
  • 57,520
  • 12
  • 104
  • 129