You can follow this example. This directive will change the background color of an element when hovered over:
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHover]' // The attribute name to use in HTML
})
export class HoverDirective {
constructor(
private el: ElementRef, // Reference to the host element
private renderer: Renderer2 // Safely manipulate DOM
) {}
// Listen for mouseenter event
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(
this.el.nativeElement,
'backgroundColor',
'lightblue'
);
}
// Listen for mouseleave event
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(
this.el.nativeElement,
'backgroundColor'
);
}
}
To use this directive:
Add it to your module's declarations:
@NgModule({
declarations: [HoverDirective],
// ...
})
Apply it in your template:
<div appHover>Hover over me!</div>