I'm building a component for my app menu. The sub-menus needs to be opened on mouseenter when the menu is in compact mode, and on click when on wide mode (both are css classes for the "nav" element inside the component).
<nav class="{{menuState}}">
<ul>
<li *ngFor="let child of menuitem.children; let i = index" class="menu-item" [ngClass]="{'display-menu': child.subOpen === true, '' : child.subOpen === false}" (mouseenter)="child.subOpen=true" (mouseleave)="child.subOpen=false" (click)="child.subOpen=true"></li>
</ul>
<nav>
How do I make the mouseenter / click events to fire only when the wrapping nav element has the relevant class?
You can make a evaluateEvent function in your component class which can register a event depending on the classname assigned to your menu item. Add a reference of the evaluateEvent function of (click) and (mouseover) event and pass in the $event and pass in the className of menu.(am assuming you are appending a different className to your menu depending on the compact and wide version).
Here is the snippet. (I have added a button for toggling the compact and wide version). The events are binded on the HelloAngular js button depending on the version - compact or wide
stackblitz link - https://stackblitz.com/edit/angular-vmpivu File -hello.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<button (click)="evaluateEvent($event,classType)"
(mouseover)="evaluateEvent($event,classType)"
[ngClass]="classType"> Hello {{name}}!</button><br/>
<br/>
<button (click)="toggleClass($event)">Toggle Class
({{this.classType}}--{{this.text}})</button>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
classType:String="compact";
text:String="mouseover bind";
toggleClass(ev)
{
if(this.classType==='compact'){this.classType=
'wide';this.text="click bind"}
else if(this.classType==='wide'){this.classType=
'compact';this.text="mouseover bind"}
}
compactHandler()
{
alert('Hi am a compact handler');
}
widehandler()
{
alert('Hi am a wide handler');
}
evaluateEvent(ev:any,classType){
if((ev.type==="click")&&(classType==="wide")){
return this.compactHandler();
}
else if((ev.type==="mouseover")&&(classType==="compact")){
return this.widehandler();
}
}
}