0

The following code generates 4 200x200 divs.

I want to set a class to a div when mouse is hovering (the class should be set only to the div that is hovered, not the other three)

<style>
   div {height: 200px; width: 200px; margin: 20px;}
   .mouseover {background-color: red;}
</style>

<div *ngFor="let a of [1,2,3,4]" 
    [class.mouseover]="mouseOvered" 
    (mouseover)="mouseOvered=true" 
    (mouseleave)="mouseOvered=false">
</div>

How can this be done without defining mouseOvered in the component?

Vingtoft
  • 13,368
  • 23
  • 86
  • 135
  • If you are simply looking at simplifying or writting less code, you could isolate this logic in a directive - though I think what you have is just fine – Damian C Nov 11 '19 at 14:46
  • The problem with the above solution is that all divs will get class 'mouseover' if a single div is hovered. I think you are right about creating a custom directive. – Vingtoft Nov 11 '19 at 14:48
  • Check this: https://stackoverflow.com/q/42633117/2050306 – robert Nov 11 '19 at 15:29

2 Answers2

2

I would recommend creating a directive to isolate each instance within the ngFor:

@Directive({
  selector: '[mouseOver]'
})
export class MouseOverDirective {

  @HostBinding('class.mouseover')
  isMouseOver = false;

  @HostListener('mouseenter')
  onEnter() {
    this.isMouseOver = true;
  }

  @HostListener('mouseleave')
  onLeave() {
    this.isMouseOver = false;
  }
}

And use it as follows:

<div *ngFor="let a of [1,2,3,4]" mouseOver></div>

StackBlitz Example

Alternative

If you prefer not creating a directive, you can also use an index map to store the condition of each instance:

Component class:

export class MyExampleComponent  {

  mouseOvered: { [index: number]: boolean } = {};

}

Component Template:

<div *ngFor="let a of [1,2,3,4]; let i = index" 
    [class.mouseover]="mouseOvered[i]" 
    (mouseover)="mouseOvered[i]=true" 
    (mouseleave)="mouseOvered[i]=false">
</div>

StackBlitz Example

Sam Herrmann
  • 6,293
  • 4
  • 31
  • 50
0

Pure css solution, based on your code:

div {
  height: 200px; 
  width: 200px; 
  margin: 20px;
  background-color: orange;
}

div:hover {
  background-color: red;
}

Stackblitz.

robert
  • 5,742
  • 7
  • 28
  • 37