How to create an attribute directive that changes element behavior on hover events

0 votes
Can Someone help me regarding How to create an attribute directive that changes element behavior on hover events?
Apr 10, 2025 in Java-Script by Nidhi
• 16,260 points
2,210 views

1 answer to this question.

0 votes

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>

answered Apr 10, 2025 by anonymous

Related Questions In Java-Script

0 votes
1 answer

How do I select an element with its name attribute in jQuery?

Hello @kartik, You can use: jQuery('[name="' + nameAttributeValue + ...READ MORE

answered Jun 11, 2020