我正在尝试使用语义UI在Angular 2中创建通用下拉控件.我有以下代码:
import {ElementRef,Component,OnInit,EventEmitter} from "angular2/core"; import {DropdownValue} from "./dropdown-value"; declare var jQuery: any; @Component({ selector: 'my-dropdown',inputs: ['selectedItem','items','label'],outputs: ['selectedItemChange'],template: ` <div class="field"> <label>{{label}}</label> <select class="ui selection dropdown" [ngModel]="selectedItem.value" (ngModelChange)="onChange($event)"> <!--<option value="" selected>Please Select</option>--> <option *ngFor="#item of items" [value]="item.value">{{item.label}}</option> </select> </div>` }) export class MyDropdownComponent implements OnInit { items: DropdownValue[]; selectedItem: DropdownValue; selectedItemChange: EventEmitter<any> = new EventEmitter(); constructor(private elementRef: ElementRef) { } ngOnInit(): any { this.items.unshift(new DropdownValue('','Please Select')); this.selectedItem = this.selectedItem || this.items[0]; //jQuery(this.elementRef.nativeElement).find('select').dropdown(); } onChange(newValue) { let selectedItem = this.items.find(item => item.value == newValue); this.selectedItemChange.emit(selectedItem); } }
这实际上工作得很好(没有Semantic UI JS样式),问题是,只要我取消注释//jQuery(this.elementRef.nativeElement)行.find(‘select’).dropdown(); “请选择”不再可见,并且不显示初始选择.
解决方法
正如Günter所说,你应该在ngAfterViewInit()中调用jQuery().dropdown().
dropdown()重置所选值.所以你必须在下拉()后重新选择所需的值:
ngAfterViewInit(){ jQuery(this.elementRef.nativeElement).find('select').dropdown({allowTab:false}); jQuery(this.elementRef.nativeElement).find('select').dropdown("set selected",this.selectedItem.value); }