247

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.

3

11 Answers 11

319

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

Sign up to request clarification or add additional context in comments.

4 Comments

how can I trigger it from angular component .ts file ?
@mayurkukadiya see my updated answer below -stackoverflow.com/a/37688325/5043867
Simple solution so I give it +1
@MayurKukadiya Simply define a boolean varibale lets say booleanVariable: boolean = false; variable with initial value to false; In mouseEnter() function just assign boolean variable to true and mouseLeave() function assign that boolean varible to false. Finally using *ngIf="booleanVariable" in the div to access it completely.
134

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

6 Comments

Why not <div (mouseover)='over()'? ;-)
@GünterZöchbauer, Is their some sort of list of all events? I looked on the angular 2 site and could not find (mouseover)
These are not Angular events but browser events.
Clearly this is the way, but does anyone have a link to the Angular documentation for this? I feel like it's super abstract and sparse. I'm just looking for a list of on-whatevers so I know what comes standard.
@Pardeep Jain, how to do add a class when hover and remove that class when mouseout?
|
38

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 )

Comments

25

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)

Comments

12

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

Comments

10

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

Comments

7

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

Comments

2
@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

Comments

1

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

Comments

0

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> 

Comments

0

HTML

<div *ngIf=" availableLocales && (availableLocales?.categories?.items)!.length > 1 " class="nav__top-nav-link--selectable" tabindex="0" (keyup.enter)="isOpen = !isOpen" (mouseenter)="mouseEnter($event)" (mouseleave)="mouseLeave($event)" #localeButton > <h4>{{ availableLocales?.heading }}</h4></div> 

TS

mouseEnter(event: any) { this.isOpen = true; if (this.isBrowser) { this.dom .getElementsByClassName('btnRequestDemo')[0] .classList.add('btnHideRequestDemo'); } } mouseLeave(event: any) { this.isOpen = false; this.dom .getElementsByClassName('btnHideRequestDemo')[0] .classList.remove('btnHideRequestDemo'); } 

Css

p:hover, h4:hover, a:hover { background-color: yellow; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.