将相同的鼠标悬停事件绑定到多个[ngClass]

时间:2018-10-01 04:45:25

标签: angular typescript ng-class

<li class="dropdown-submenu dropdown pointer" (mouseover)="toogleClickEvent($event)" (mouseout)="toogleClickEvent($event)"
  [ngClass]="show">
  <a class="test" tabindex="-1"><i class="fa fa-language " aria-hidden="true"></i>{{'Language' | translate}}</a>
  <ul class="dropdown-menu">
    <li class="pointer"><a (click)="changeLang('en')">{{'English' | translate}}</a></li>
  </ul>
</li>

<li class="dropdown-submenu dropdown pointer" (mouseover)="toogleClickEvent($event)" (mouseout)="toogleClickEvent($event)"
  [ngClass]="show1">
  <a href="#"><i class="fa fa-gear" aria-hidden="true"></i>&nbsp;&nbsp;{{'Settings' | translate}}</a>
  <ul class="dropdown-menu">
    <li class="pointer"><a>{{'Default' | translate}}</a></li>
  </ul>
</li>

app.ts

export class app{
   show: string;
   toogleClickEvent($event) {
      this.show =   $event.type == 'mouseover' ? 'open' : '';
   }
}

在上面的代码中,我有两个下拉菜单,我在两个下拉菜单中都调用toogleClickEvent(),但是由于相同的方法和两个下拉菜单值的相同[ngclass]相同,我得到了  那么如何使用一种方法而不是创建新方法来处理两种不同的[ngclss]

2 个答案:

答案 0 :(得分:0)

您可以在函数内部传递标签,例如

toogleClickEvent($event,'test') 

然后在您的 ts 文件中,执行以下操作

toogleClickEvent($event,type) {
   if(type=='test') {
      this.show =   $event.type == 'mouseover' ? 'open' : '';
 }
   if(type=='test1') {
      this.show1 =   $event.type == 'mouseover' ? 'open' : '';
 }
}

答案 1 :(得分:0)

使用(mouseover)="show='open'" (mouseout)="show=''" [ngClass]="show"

<li class="dropdown-submenu dropdown pointer" (mouseover)="show='open'" (mouseout)="show=''"
  [ngClass]="show">
  ....
</li>

<li class="dropdown-submenu dropdown pointer" (mouseover)="show1='open'" (mouseout)="show1=''"
  [ngClass]="show1">
  ....
</li>