Created
July 10, 2016 03:15
-
-
Save ihadeed/17325c111d0389774d7da209a19b9550 to your computer and use it in GitHub Desktop.
Angular2 Component: Semantic UI Dropdown
This file contains 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 {Component, ElementRef, AfterViewInit, Output, EventEmitter, Input, Self} from '@angular/core'; | |
import {ControlValueAccessor, NgModel} from '@angular/common'; | |
declare var $: any; | |
@Component({ | |
selector: 'dropdown', | |
template: ` | |
<select class="ui dropdown" [(ngModel)]="selectedOption"> | |
<option value="">Select one</option> | |
<option *ngFor="let item of items" [value]="item[valueField]">{{item[textField]}}</option> | |
</select> | |
`, | |
providers: [NgModel] | |
}) | |
export class DropdownComponent implements AfterViewInit, ControlValueAccessor { | |
@Input() valueField: string; | |
@Input() textField: string; | |
@Input() items: any[] = []; | |
@Output() change: EventEmitter<string> = new EventEmitter<string>(); | |
public onChange: any = Function.prototype; | |
public onTouched: any = Function.prototype; | |
private _selectedOption: string = ''; | |
get selectedOption(): string { | |
return this._selectedOption; | |
} | |
set selectedOption(option: string){ | |
if(option === this._selectedOption) return; | |
this._selectedOption = option; | |
this.writeValue(option); | |
} | |
constructor(private parentElement: ElementRef, @Self() private self: NgModel){ | |
this.self.valueAccessor = this; | |
} | |
ngAfterViewInit(): void { | |
let selectElement: HTMLElement = this.parentElement.nativeElement.children[0]; | |
console.log(this.parentElement, selectElement); | |
$(selectElement).dropdown(); | |
} | |
writeValue (value: string): void { | |
this.self.viewToModelUpdate(value); | |
this.change.emit(value); | |
} | |
registerOnChange(fn: (_: any) => void): void { this.onChange = fn; } | |
registerOnTouched(fn: () => void): void { this.onTouched = fn; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is nice. I'm working on my own DropdownComponent and was able to steal some ideas from this. I'm not understanding some of the code here though (I'm new to Angular). Why are you passing the parentElement and self into the component?
It seems to me that there's custom code that angular handles on its own. For instance,
writeValue()
. I don't understand the full consequences of those choices. Could you explain why you made these choices? I'm sure I'm missing some valuable information.Thank you!