How can I add a class to an element on hover?

Not to dirty the code I just coded simple hover-class directive.

<span hover-class="btn-primary" class="btn" >Test Me</span>

Running Sample

Code Editor stackblitz

Here below the directive,

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

@Directive({
    selector: '[hover-class]'
})
export class HoverClassDirective {

    constructor(public elementRef: ElementRef) { }
    @Input('hover-class') hoverClass: any;

    @HostListener('mouseenter') onMouseEnter() {
        this.elementRef.nativeElement.classList.add(this.hoverClass);
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.elementRef.nativeElement.classList.remove(this.hoverClass);
    }

}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)