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");
});
作爲一個事實菜單,它剛剛打開後關閉。如何解決它,爲什麼會發生這種情況?
謝謝。這解決了我的問題! – dantey89