Angular 2 Hover event

JavascriptAngularEventsHover

Javascript Problem Overview


In the new Angular2 framework, does anyone know the proper way to do a hover like an event?

In Angular1 there was ng-Mouseover, but that doesn't seem to have been carried over.

I've looked through the docs and haven't found anything.

Javascript Solutions


Solution 1 - Javascript

If you want to perform a hover like event on any HTML element, then you can do it like this.

HTML

Div A

Div B

Component

import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'basic-detail',
    templateUrl: 'basic.component.html',
})
export class BasicComponent{

   mouseEnter(div : string){
      console.log("mouse enter : " + div);
   }

   mouseLeave(div : string){
     console.log('mouse leave :' + div);
   }
}

You should use both mouseenter and mouseleave events in order to fully implement functional hover events in angular 2.

Solution 2 - Javascript

yes there is on-mouseover in angular2 instead of ng-Mouseover like in angular 1.x so you have to write this :-

hello mouseover

over(){
    console.log("Mouseover called");
  }

As @Gunter Suggested in comment there is alternate of on-mouseover we can use this too. Some people prefer the on- prefix alternative, known as the canonical form.

Update

HTML Code -

hello mouseover

Controller/.TS Code -

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  over(){
    console.log("Mouseover called");
  }

  out(){
    console.log("Mouseout called");
  }
}

Working Example

Some other Mouse events can be used in Angular -

(mouseenter)="myMethod()"
(mousedown)="myMethod()"
(mouseup)="myMethod()"

Solution 3 - Javascript

You can do it with a host:

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[myHighlight]',
  host: {
    '(mouseenter)': 'onMouseEnter()',
    '(mouseleave)': 'onMouseLeave()'
  }
})
export class HighlightDirective {
  private _defaultColor = 'blue';
  private el: HTMLElement;

  constructor(el: ElementRef) { this.el = el.nativeElement; }

  @Input('myHighlight') highlightColor: string;

  onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
  onMouseLeave() { this.highlight(null); }

   private highlight(color:string) {
    this.el.style.backgroundColor = color;
  }

}

Just adapt it to your code (found at: https://angular.io/docs/ts/latest/guide/attribute-directives.html )

Solution 4 - Javascript

If you are interested in the mouse entering or leaving one of your components you can use the @HostListener decorator:

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

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {

  @HostListener('mouseenter') 
  onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave') 
  onMouseLeave() {
    this.highlight(null);
  }

...

}

As explained in the link in @Brandon comment to OP (https://angular.io/docs/ts/latest/guide/attribute-directives.html)

Solution 5 - Javascript

Simply do (mouseenter) attribute in Angular2+...

In your HTML do:

<div (mouseenter)="mouseHover($event)">Hover!</div> 

and in your component do:

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

@Component({
  selector: 'component',
  templateUrl: './component.html',
  styleUrls: ['./component.scss']
})

export class MyComponent implements OnInit {
   
  mouseHover(e) {
    console.log('hovered', e);
  }
} 

Solution 6 - Javascript

For handling the event on overing, you can try something like this (it works for me):

In the Html template:

<div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
  <img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
</div>

In the angular component:

    onHovering(eventObject) {
    console.log("AlertsBtnComponent.onHovering:");
    var regExp = new RegExp(".svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
		srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));		
    }

   }
   onUnovering(eventObject) {
    console.log("AlertsBtnComponent.onUnovering:");
    var regExp = new RegExp("_h.svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
		srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
    }
}

Solution 7 - Javascript

If the mouse over for all over the component is your option, you can directly is @hostListener to handle the events to perform the mouse over al below.

  import {HostListener} from '@angular/core';

  @HostListener('mouseenter') onMouseEnter() {
    this.hover = true;
    this.elementRef.nativeElement.addClass = 'edit';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.hover = false;
    this.elementRef.nativeElement.addClass = 'un-edit';
  }

Its available in @angular/core. I tested it in angular 4.x.x

Solution 8 - Javascript

@Component({
    selector: 'drag-drop',
    template: `
        <h1>Drag 'n Drop</h1>
        <div #container 
             class="container"
             (mousemove)="onMouseMove( container)">
            <div #draggable 
                 class="draggable"
                 (mousedown)="onMouseButton( container)"
                 (mouseup)="onMouseButton( container)">
            </div>
        </div>`,

})

http://lishman.io/angular-2-event-binding

Solution 9 - Javascript

In your js/ts file for the html that will be hovered

@Output() elemHovered: EventEmitter<any> = new EventEmitter<any>();
onHoverEnter(): void {
    this.elemHovered.emit([`The button was entered!`,this.event]);
}

onHoverLeave(): void {
    this.elemHovered.emit([`The button was left!`,this.event])
}

In your HTML that will be hovered

 (mouseenter) = "onHoverEnter()" (mouseleave)="onHoverLeave()"

In your js/ts file that will receive info of the hovering

elemHoveredCatch(d): void {
    console.log(d)
}

In your HTML element that is connected with catching js/ts file

(elemHovered) = "elemHoveredCatch($event)"

Solution 10 - Javascript

If you're looking for just a hover effect, use Hover.css.

  • npm i hover.css
  • in file angular.json property projects.architect.build.options.styles --> add this line to the array: node_modules/hover.css/scss/hover.scss

Use any of their classes on the element you want the effect on, i.e.:

<div *ngFor="let source of sources">
    <div class="row justify-content-center">
        <div class="col-12 hvr-glow">
            <!-- My content -->
        </div>
    </div>
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoninView Question on Stackoverflow
Solution 1 - JavascriptVikash DahiyaView Answer on Stackoverflow
Solution 2 - JavascriptPardeep JainView Answer on Stackoverflow
Solution 3 - JavascriptbeneView Answer on Stackoverflow
Solution 4 - JavascriptpaulView Answer on Stackoverflow
Solution 5 - JavascriptAlirezaView Answer on Stackoverflow
Solution 6 - JavascriptDudiView Answer on Stackoverflow
Solution 7 - JavascriptAniruddha DasView Answer on Stackoverflow
Solution 8 - JavascriptClayton K. N. PassosView Answer on Stackoverflow
Solution 9 - JavascriptLyudmil PetrovView Answer on Stackoverflow
Solution 10 - JavascriptxinthoseView Answer on Stackoverflow