Skip to content

Instantly share code, notes, and snippets.

@vbelcik
Created May 15, 2017 07:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vbelcik/5d638bd919377a5f1e7b7b362878ec31 to your computer and use it in GitHub Desktop.
Save vbelcik/5d638bd919377a5f1e7b7b362878ec31 to your computer and use it in GitHub Desktop.
Angular4 dropdown directive for bootstrap - enhanced
import { Directive, HostListener, HostBinding, OnDestroy } from '@angular/core';
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective implements OnDestroy {
private timer = null;
private isMouseInside: boolean = false;
@HostBinding('class.open') isOpen: boolean = false;
@HostListener('click') toggleOpen() {
this.isOpen = !this.isOpen;
}
@HostListener('document:click') onDocumentClick() {
if (!this.isMouseInside)
this.isOpen = false;
}
@HostListener('mouseleave') onMouseLeave() {
this.isMouseInside = false;
this.scheduleTimeout();
}
@HostListener('mouseenter') onMouseEnter() {
this.isMouseInside = true;
this.cancelTimeout();
}
scheduleTimeout() {
this.cancelTimeout();
this.timer = setTimeout(() => {
this.timer = null;
this.isOpen = false;
}, 500);
}
cancelTimeout() {
let t = this.timer;
this.timer = null;
if (t !== null)
clearTimeout(t);
}
ngOnDestroy() {
this.cancelTimeout();
}
// not functional; blur
// @HostListener('blur') removeOpen() {
// this.isOpen = false;
// }
// note: not sufficient for dropdown button
// @HostListener('mouseleave') removeOpen() {
// this.isOpen = false;
// }
}
@diemgomez
Copy link

@vbelcik thank you for sharing this code!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment