Angular 2 Hover event
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()"
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.
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 )