subscribing when mouseover on particular element in the DOM

666 views Asked by At

I need to subscribe & do some actions, when mouseover on particular elements in the DOM.

For Example: home.component.html

        <div class="container">
              <div class="row1"> </div>
              <div class="row2"> </div>
              <div class="row3"> </div>
        </div>

home.component.ts:

         import {
                 AfterViewInit,
                 Component,
                 Input,
                 OnInit,
                } from '@angular/core';

                @Component({
                             selector: 'app-home',
                             templateUrl: './home.component.html',
                             styleUrls: ['./home.component.scss'],
                           })
          export class homeComponent implements OnInit {
          
               public hover: boolean;

               constructor() {}

               ngOnInit(): void {
                     this.hover= true;       // it may be false also.
               }

          }

In the above example when mouseover on row1 & row3 elements then I need to subscribe. Also I need to check one variable called "hover", if it is true then only I need todo the above action(mouseover). If the variable is false then no need to check for mouseover(no need to do any action), just I need to unsubscribe it. Can any one help me to achieve this.

2

There are 2 answers

0
MoxxiManagarm On

Simply react on mouseenter and mouseleave event.

<div (mouseenter)="setHover(true)" (mouseleave)="setHover(false)">Hover me to see additional text</div>
<div *ngIf="shouldShow">HELLO WORLD</div>
export class AppComponent  {
  canHover: boolean = true;
  isHover: boolean = false;

  setHover(hover: boolean) {
   this.isHover = hover;
  }

  get shouldShow() {
    return this.canHover && this.isHover;
  }
}

See this example in action: https://stackblitz.com/edit/angular-ivy-2bdafy?file=src/app/app.component.ts

0
Fateh Mohamed On

in case you wanna subscribe to events from multiple elements, you can use fromEvent on your 2 elements row1 and row2, merge them and filter relative to your hover boolean, combineLastest will emit a value if one of your two hover events is triggered

import { merge, fromEvent  } from 'rxjs';
import { map, filter } from 'rxjs/operators';

@ViewChild('row1', { static: true }) row1: ElementRef;
@ViewChild('row2', { static: true }) row2: ElementRef;

merge(
 fromEvent(this.row1.nativeElement, 'mouseover'),
 fromEvent(this.row2.nativeElement, 'mouseover')
).pipe(
 filter(_ => !!this.hover),
 map((event) => {
  // some control here
 })
).subscribe();