Home  >  Q&A  >  body text

How to change div background based on component field on mouseover

I have a div that when it is hovered, the background color changes, I also need to select the color based on an element in the component.

<div *ngFor="let u of users;" 
  [style:hover.background-color] = "u.selected ? 'red' : 'blue' ">
</div>

P粉968008175P粉968008175374 days ago500

reply all(1)I'll reply

  • P粉520545753

    P粉5205457532023-09-13 00:19:30

    From the comment link above:

    "Actually this is not an Angular problem: pseudo-elements are not part of the DOM tree and therefore do not expose any DOM API that can be used to interact with them."

    So you can use CSS variables instead:

    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>

    reply
    0
  • Cancelreply