2017-03-16 53 views
0

我的組件模板中有一個select元素,它連接了selectedEmp模型。我希望能夠更新組件中的selectedEmp,並在select元素中顯示正確的值。我目前的設置不會讓這種情況發生。相反,選擇值不會顯示selectedEmp。我控制檯記錄了selectedEmp,其值正在改變。我認爲這是因爲當我通過組件做選項時,選項元素從未設置爲任何值。有沒有人知道一種方法來做到這一點。Angular2 - 更新組件中的選擇模板

Component.html

 <select name="sel1" class="form-control" (ngModelChange)="onChange($event.target.value)" [(ngModel)]="selectedEmp"> 
      <option [value]="employee" *ngFor="let employee of employees"> 
       {{employee}} 
      </option> 
     </select> 

Component.ts

employees:Array<string> = ["Andrew","Allen","Kevin","Phil"]; 
visable:boolean = false; 
selectedEmp:any = null; 
constructor(){} 
// Selection change 
onChange(value:any):void { 
    console.log(value); 
} 
updateModel(){ 
    this.selectedEmp = "Allen" 
} 
+0

沒有真正理解這個問題,你可以形容它遠一點?什麼時候updateModel被調用?模型中的模型沒有更新,究竟在哪裏? – Alex

回答

0

這不是從你的問題很清楚,但我沒有看到你(ngModelChange)事件綁定一個錯誤,因爲該項目是字符串,$event.target.value fails請嘗試(ngModelChange)="onChange($event)"

但這也僅僅是控制檯,無論如何,所以刪除它的葉子:

<button type="button" (click)="updateModel()">Select Allen</button> 

<select name="sel1" [(ngModel)]="selectedEmp"> 
     <option [value]="employee" *ngFor="let employee of employees"> 
      {{employee}} 
     </option> 
</select>