|
1 | | -import {Component, ViewEncapsulation} from '@angular/core'; |
| 1 | +import { |
| 2 | + Component, |
| 3 | + ElementRef, |
| 4 | + EventEmitter, |
| 5 | + Output, |
| 6 | + Renderer, |
| 7 | + ViewEncapsulation |
| 8 | +} from '@angular/core'; |
| 9 | +import {ENTER, SPACE} from '../core/keyboard/keycodes'; |
2 | 10 |
|
3 | 11 | @Component({ |
4 | 12 | moduleId: module.id, |
5 | 13 | selector: 'md-option', |
6 | | - template: ``, |
| 14 | + host: { |
| 15 | + 'role': 'option', |
| 16 | + 'tabindex': '0', |
| 17 | + '[class.md-selected]': 'selected', |
| 18 | + '[attr.aria-selected]': 'selected.toString()', |
| 19 | + '(click)': 'select()', |
| 20 | + '(keydown)': '_handleKeydown($event)' |
| 21 | + }, |
| 22 | + templateUrl: 'option.html', |
7 | 23 | styleUrls: ['select.css'], |
8 | 24 | encapsulation: ViewEncapsulation.None |
9 | 25 | }) |
10 | | -export class MdOption {} |
| 26 | +export class MdOption { |
| 27 | + private _selected = false; |
| 28 | + |
| 29 | + /** Event emitted when the option is selected. */ |
| 30 | + @Output() onSelect = new EventEmitter(); |
| 31 | + |
| 32 | + constructor(private _element: ElementRef, private _renderer: Renderer) {} |
| 33 | + |
| 34 | + /** Whether or not the option is currently selected. */ |
| 35 | + get selected(): boolean { |
| 36 | + return this._selected; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * The displayed value of the option. It is necessary to show the selected option in the |
| 41 | + * select's trigger. |
| 42 | + * TODO(kara): Add input property alternative for node envs. |
| 43 | + */ |
| 44 | + get viewValue(): string { |
| 45 | + return this._getHostElement().textContent.trim(); |
| 46 | + } |
| 47 | + |
| 48 | + /** Selects the option. */ |
| 49 | + select(): void { |
| 50 | + this._selected = true; |
| 51 | + this.onSelect.emit(); |
| 52 | + } |
| 53 | + |
| 54 | + /** Deselects the option. */ |
| 55 | + deselect(): void { |
| 56 | + this._selected = false; |
| 57 | + } |
| 58 | + |
| 59 | + /** Sets focus onto this option. */ |
| 60 | + focus(): void { |
| 61 | + this._renderer.invokeElementMethod(this._getHostElement(), 'focus'); |
| 62 | + } |
| 63 | + |
| 64 | + /** Ensures the option is selected when activated from the keyboard. */ |
| 65 | + _handleKeydown(event: KeyboardEvent): void { |
| 66 | + if (event.keyCode === ENTER || event.keyCode === SPACE) { |
| 67 | + this.select(); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + _getHostElement(): HTMLElement { |
| 72 | + return this._element.nativeElement; |
| 73 | + } |
| 74 | + |
| 75 | +} |
0 commit comments