Skip to content

Instantly share code, notes, and snippets.

@vbelcik
Last active May 13, 2017 10:49
Show Gist options
  • Save vbelcik/2b0ef6a5ac8dccad555c3fd4f039998d to your computer and use it in GitHub Desktop.
Save vbelcik/2b0ef6a5ac8dccad555c3fd4f039998d to your computer and use it in GitHub Desktop.
Angular4 dropdown directive for bootstrap
import { Directive, HostListener, HostBinding, OnDestroy } from '@angular/core';
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective implements OnDestroy {
private timer = null;
@HostBinding('class.open') isOpen: boolean = false;
@HostListener('click') toggleOpen() {
this.isOpen = !this.isOpen;
}
@HostListener('mouseleave') scheduleTimeout() {
this.cancelTimeout();
this.timer = setTimeout(() => {
this.timer = null;
this.isOpen = false;
}, 1000);
}
@HostListener('mouseenter') 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;
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment