LordGrim
LordGrim

Reputation: 70

Hover intent implementation in angular 2+

I'm having a hard time finding anything for implementing hover intent in angular 2. Open to any suggestions.

Upvotes: 1

Views: 459

Answers (2)

Jiri Pelnar
Jiri Pelnar

Reputation: 63

You can implement this using the hoverintent plugin for example

You can create your own angular attribute directive and hook the plugin to the element on which this directive is used on inside this directive's ngOnInit method like this for example:

public ngOnInit()
{
    this.HoverListener = hoverintent(this.Element.nativeElement,
        () =>
        {
            // Handler in - do any action here, like opening a menu for example
        },
        () =>
        {
            // Handler out - do any action here, like closing a menu for example
        } 
    );
}

you need to get the Element reference injected in the constructor the usual way:

constructor(protected Element: ElementRef)
{
}

also do not forget to call the remove() method in the directive ngOnDestroy method to prevent any memory leaks:

public ngOnDestroy()
{         
    this.HoverListener.remove();     
}

On the project I used this plugin on I chose to load the plugin javascript source file as part of the page and did not attempt to include it in the rollup bundle that I use for bundling AOT compiled application.

Upvotes: 2

Max Gaurav
Max Gaurav

Reputation: 1913

For hover implementation in angular the use of mouseenter and mouseleave events are required to be used over elements

Following example will help you out:

HTML

<p (mouseenter)="onMouseEnter($event)" (mouseleave)="onMouseLeave($event)">Some value</p>

Code

public onMouseEnter($event): void {
   //your code when the mouse cursor enters the element
}

public onMouseLeave($event): void {
   //your code when the mouse cursor leaves the element
}

Upvotes: 1

Related Questions