Created
May 15, 2017 07:36
-
-
Save vbelcik/5d638bd919377a5f1e7b7b362878ec31 to your computer and use it in GitHub Desktop.
Angular4 dropdown directive for bootstrap - enhanced
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@vbelcik thank you for sharing this code!!