[英]Angular2 - update select template from component
我的組件模板中有一個selected模型,它連接了selectedEmp模型。我希望能夠更新組件中的selectedEmp並在select元素中顯示正確的值。 我當前的設置不會讓這種情況發生。 相反,選擇值不顯示selectedEmp。 我在控制台上記錄了selectedEmp,它的值正在更改。 我認為這是因為通過組件執行操作時,option元素從未設置為任何值。 有誰知道做到這一點的方法。
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"
}
從您的問題中還不清楚,但是我確實在您的(ngModelChange)
事件綁定上看到一個錯誤,因為這些項是字符串,所以$event.target.value fails
try (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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.