2017-05-27 66 views
0

我有一個具有多個下拉菜單的導航欄。我正在使用由ngx-bootstrap提供的指令來處理下拉行爲。我想通過在mouseover上打開下拉菜單並在mouseout上關閉它們來添加自定義功能。我需要在mouseout上調用BsDropdownToggleDirective的onEsc()函數。當我用@ViewChild實現這個時,它僅適用於第一個下拉菜單,但不適用於第二個下拉菜單。當我刪除第一個下拉菜單時,第二個下拉菜單就起作用了。如何打開onEsc()打開哪個下拉菜單?如果在同一模板中有多個指令實例,我該如何調用指令的方法?

頂級菜單links.component.ts

import { Component, ViewChild } from '@angular/core'; 
import { BsDropdownToggleDirective } from 'ngx-bootstrap/dropdown'; 

@Component({ 
    selector: 'top-nav-main', 
    templateUrl: './top-menu-links.component.html', 
    // styleUrls: [ './top-menu-links.component.scss' ] 
}) 
export class TopMenuLinksComponent { 
    @ViewChild(BsDropdownToggleDirective) dropdown:BsDropdownToggleDirective; 

    public closeDropdown():void { 
     this.dropdown.onEsc(); 
    } 

} 

頂級菜單links.component.html

<li class="dropdown" bsDropdown triggers="mouseover" > 
       <a bsDropdownToggle dropdown-toggle data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" (mouseout)="closeDropdown()">Features<span class="caret"></span></a> 
       <ul class="dropdown-menu" *bsDropdownMenu> 
        <li class="nav-item"><a class="nav-link" routerLink="feature-1">Feature 1</a></li> 
        <li class="nav-item"><a class="nav-link" routerLink="feature-2">Feature 2</a></li> 
        <li class="nav-item"><a class="nav-link" routerLink="feature-3">Feature 3</a></li> 
       </ul> 
      </li> 
      <li class="dropdown" bsDropdown triggers="mouseover"> 
       <a bsDropdownToggle dropdown-toggle data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" (mouseout)="closeDropdown()">Company<span class="caret"></span></a> 
       <ul class="dropdown-menu" *bsDropdownMenu> 
        <li class="nav-item"><a class="nav-link" routerLink="app-about-us">About</a></li> 
        <li class="nav-item"><a class="nav-link" routerLink="app-faq">Frequently Asked Questions</a></li> 
        <li class="nav-item"><a class="nav-link" routerLink="app-contact-us">Contact</a></li> 
       </ul> 
      </li> 
+0

你必須使用[@ViewChildren(https://angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html)代替@ViewChild – mbppv

+0

當我將ViewChild更改爲ViewChildren時,出現TypeError:this.dropdown.onEsc不是函數。我必須做其他事情才能使ViewChildren發揮作用嗎? –

+0

爲什麼你明確使用'directive' ** ** – Aravind

回答

1

正如上面提到的,你必須使用@ViewChildren裝飾。請給一個嘗試這樣的:

import { Component, ViewChildren, QueryList } from '@angular/core'; 
import { BsDropdownToggleDirective } from 'ngx-bootstrap/dropdown'; 

@Component({ 
    selector: 'top-nav-main', 
    templateUrl: './top-menu-links.component.html', 
    // styleUrls: [ './top-menu-links.component.scss' ] 
}) 
export class TopMenuLinksComponent { 
    @ViewChildren(BsDropdownToggleDirective) dropdowns: QueryList<BsDropdownToggleDirective>; 

    public closeDropdown():void { 
     this.dropdowns.forEach((dropdown) => { 
      dropdown.onEsc() 
     }) 
    } 

} 
相關問題