[javascript] Angular 2 Hover event

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.

This question is related to javascript angular events hover

The answer is


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

HTML

 <div (mouseenter) ="mouseEnter('div a') "  (mouseleave) ="mouseLeave('div A')">
        <h2>Div A</h2>
 </div> 
 <div (mouseenter) ="mouseEnter('div b')"  (mouseleave) ="mouseLeave('div B')">
        <h2>Div B</h2>
 </div>

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 inorder to implement fully functional hover events in angular 2.


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"));
    }
}

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 )


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)


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


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);
  }
} 

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

<div on-mouseover='over()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

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 -

<div (mouseover)='over()' (mouseout)='out()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

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()"

@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


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)"

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to events

onKeyDown event not working on divs in React Detect click outside Angular component Angular 2 Hover event Global Events in Angular How to fire an event when v-model changes? Passing string parameter in JavaScript function Capture close event on Bootstrap Modal AngularJs event to call after content is loaded Remove All Event Listeners of Specific Type Jquery .on('scroll') not firing the event while scrolling

Examples related to hover

Angular 2 Hover event How can I access a hover state in reactjs? CSS disable hover effect How to remove/ignore :hover css style on touch devices Spin or rotate an image on hover How to make in CSS an overlay over an image? How to display and hide a div with CSS? simple Jquery hover enlarge Changing image on hover with CSS/HTML CSS On hover show another element