2

I have a div I want to hover, as soon as it's hovered I want to show a text that moves with the cursor but solely on the y-axis. You can find the effect I'm talking about on this website hovering an image.

My code so far:

<div class="scroll-container align-self-center">
    <div class="cart-container" *ngFor="let cart of carts; let i = index" routerLink="project/{{cart.title}}">
      <div class="cart-item cursor-hover position-relative d-flex justify-content-center" [ngStyle]="{'background-image': 'url(' + cart.image + ')'}" [class.cart-item-even]="i % 2 !== 0"
      (mouseenter)="cartHovered(i)" (mouseleave)="cartLeft()">
        <h1 class="hover-title" [style.display]="i === hoveredCart ? 'block' : 'none'">{{cart.title}}</h1>
      </div>
    </div>
</div>

TypeScript:
cartHovered(i) {
  this.backgroundColor = this.carts[i].backgroundColor;
  this.hoveredCart = i;
}

cartLeft() 
  this.hoveredCart = -1;
}

How can I achieve this effect using Angular when hovering .cart-item?

Tom
  • 3,672
  • 6
  • 20
  • 52
  • 1
    Here is a good example for mouse move event. https://stackoverflow.com/questions/46389002/how-to-listen-for-mousemove-event-on-document-object-in-angular and then you just need to set the style of your box. absolute position and the x axis to whatever the mouse event gives you – ill Dec 11 '19 at 15:57

1 Answers1

2
<h1 #floatingElement clas=...
--------------------------------
import {fromEvent} from 'rxjs';
....
@ViewChildren('floatingElement') floatingElements;
constructor(ngZone: NgZone){}
ngOnInit() {
  this.ngZone.runOutsideAngular(() => {
     fromEvent(window, 'mousemove').pipe(
       filter(() => this.hoveredCard != -1),
     ).subscribe(({clientY}) => this.floatingElements.toArray()[this.hoveredCard].nativeElement
       .style.top = clientY) // <-- offset should be adjusted depending on this cursor Y

  })
}

angular thing here is ngZone.runOutsideAngular and it is used to stop angular from spamming change detection on every event

Andrei
  • 10,117
  • 13
  • 21