2017-06-13 60 views
0

我寫角2應用程序和裏面我已經寫上引導角2的addEventListener內部指令

<li class="dropdown" dropdown> 
    <a class="dropdown-toggle" data-toggle="dropdown"> 
     User <span class="caret"></span> 
    </a> 
    <ul class="dropdown-menu" aria-labelledby="download"> 
     <li><a routerLink="/user/profile">My Profile</a></li> 
     <li><a (click)="logout()">Log Out</a></li> 
    </ul> 
</li> 

所有我要的是寫下一個小的指令,用於切換菜單下拉菜單。到此爲止:

@Directive({ 
    selector: "[dropdown]" 
}) 
export class DropdownDirective implements OnInit { 

    private isOpen = false; 
    private defaultClassName: string; 

    @HostListener('click') toggle() {    

    let that = this; 

    if (!this.isOpen) { 

     this.elRef.nativeElement.className = this.defaultClassName + " open"; 

     document.addEventListener("click",() => {    
      that.elRef.nativeElement.className = that.defaultClassName; 
      that.isOpen = false; 
      document.removeEventListener("click"); 
     }); 

     this.isOpen = !this.isOpen; 
    } 


    } 

    constructor(private elRef: ElementRef) { 

    }  

    ngOnInit(): void { 
     this.defaultClassName = this.elRef.nativeElement.className; 
    } 

} 

看起來不錯。但不起作用。經過簡短的調試後,我發現事件偵聽器被添加到文檔中,在它被分配之後觸發。

document.addEventListener("click",() => { 
        that.elRef.nativeElement.className = that.defaultClassName; 
        that.isOpen = false; 
        document.removeEventListener("click"); 
}); 

作爲一個事實菜單,它剛剛打開後關閉。如何解決它,爲什麼會發生這種情況?

回答

2

我已經用@HostListener()解決了同樣的情況。在零件保持下拉:

@HostListener('document:click', ['$event']) 
 
private clickAnywhere(event: MouseEvent): void { 
 
\t if (this.IsSelected && !this.elementRef.nativeElement.contains(event.target)) { 
 
\t \t this.IsSelected = false; 
 
\t } 
 
}

this.IsSelected是綁定屬性我用它來顯示下拉。 if()中的條件是檢查用戶是否點擊了菜單或文檔正文。

確保注入elementRef到構造這樣你就可以訪問所提供的HTML,以檢查是否是被點擊了什麼: public constructor(private elementRef: ElementRef) { }

你可以找到更多關於HostListener here

+1

謝謝。這解決了我的問題! – dantey89