|
| 1 | +import { Directive, HostBinding, HostListener, Input, Optional } from '@angular/core'; |
| 2 | +import { DropdownService } from '../dropdown.service'; |
| 3 | +import { DropdownComponent } from '../dropdown/dropdown.component'; |
| 4 | + |
| 5 | +@Directive({ |
| 6 | + selector: '[cDropdownClose]', |
| 7 | + exportAs: 'cDropdownClose' |
| 8 | +}) |
| 9 | +export class DropdownCloseDirective { |
| 10 | + |
| 11 | + /** |
| 12 | + * Disables a dropdown-close directive. |
| 13 | + * @type boolean |
| 14 | + * @default undefined |
| 15 | + */ |
| 16 | + @Input() disabled?: boolean; |
| 17 | + |
| 18 | + constructor( |
| 19 | + private dropdownService: DropdownService, |
| 20 | + @Optional() public dropdown?: DropdownComponent |
| 21 | + ) { } |
| 22 | + |
| 23 | + @HostBinding('class') |
| 24 | + get hostClasses(): any { |
| 25 | + return { |
| 26 | + disabled: this.disabled |
| 27 | + }; |
| 28 | + } |
| 29 | + |
| 30 | + @HostBinding('attr.tabindex') |
| 31 | + @Input() |
| 32 | + set tabIndex(value: string | number | null) { |
| 33 | + this._tabIndex = value; |
| 34 | + } |
| 35 | + get tabIndex() { |
| 36 | + return this.disabled ? '-1' : this._tabIndex; |
| 37 | + } |
| 38 | + private _tabIndex: string | number | null = null; |
| 39 | + |
| 40 | + @HostBinding('attr.aria-disabled') |
| 41 | + get isDisabled(): boolean | null { |
| 42 | + return this.disabled || null; |
| 43 | + } |
| 44 | + |
| 45 | + @HostListener('click', ['$event']) |
| 46 | + private onClick($event: MouseEvent): void { |
| 47 | + this.dropdownService.toggle({ visible: false, dropdown: this.dropdown }); |
| 48 | + } |
| 49 | + |
| 50 | + @HostListener('keyup', ['$event']) |
| 51 | + private onKeyUp($event: KeyboardEvent): void { |
| 52 | + if ($event.key === 'Enter') { |
| 53 | + this.dropdownService.toggle({ visible: false, dropdown: this.dropdown }); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments