0

我正在为我的应用程序菜单构建一个组件。当菜单处于紧凑模式时,需要在 mouseenter 上打开子菜单,而在宽模式下需要在单击时打开子菜单(两者都是组件内“nav”元素的 css 类)。

<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>

如何使 mouseenter / click 事件仅在包装导航元素具有相关类时触发?

4

1 回答 1

0

您可以在组件类中创建一个 evaluateEvent 函数,该函数可以根据分配给菜单项的类名注册事件。添加(单击)和(鼠标悬停)事件的评估事件函数的引用,并传入 $event 并传入菜单的类名。(假设您根据紧凑和宽版本将不同的类名附加到菜单) .

这是片段。(我添加了一个用于切换紧凑型和宽型版本的按钮)。事件绑定在 HelloAngular js 按钮上,具体取决于版本 - 紧凑型或宽型

stackblitz 链接 - https://stackblitz.com/edit/angular-vmpivu 文件 -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();
                        }
                    } 
                    }
于 2019-02-23T10:57:17.130 回答