2016-07-30 155 views
6

我似乎無法解決如何輕鬆設置值作爲選擇下拉列表的默認值。角度2選擇選項默認值

我當前的代碼

<select class="form-control" ngControl="modID" #modID="ngForm"> 
     <option *ngFor="let module of modules" [value]="module._id">{{module.moduleName}}</option> 
</select> 

我曾嘗試用[選擇]裝飾玩,但不能工作如何得到它的工作。

給出我有此modInst JSON對象下面:從所有modules._id(模塊)來選擇

{ 
"_id": 5, 
"semester": "Tri 3", 
"year": 2018, 
"__v": 0, 
"modID": [ 
    { 
    "_id": 6, 
    "moduleLeader": "Jake Groves", 
    "moduleName": "Software Implementation", 
    "__v": 0 
    } 
] 
}, 

我想modInst.modID [0] ._ id爲最新填充選擇列表

任何簡單的方法來做到這一點?

編輯:

我已經嘗試添加[selected]="module._id == modInst.modID[0]._id"但我沒有得到任何成功上使其選擇的值

我也試過[ngValue]="modInst.modID[0]._id",它仍然不會選擇模塊ID 6列表

最後此外...我已經試過手動「選擇」,它仍然無法在負荷做出選擇的值[selected]="module._id == '7'"

回答

11

您可以使用[(ngModel)]執行此操作。

<select [(ngModel)]="selectedModule"> 
    <option *ngFor="let module of modules" [value]="module._id"> {{module.moduleName}}/option> 
    </select> 

例如

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'awesome-component', 
    template: ` 
    <select [(ngModel)]="selectedModule"> 
    <option *ngFor="let module of modules" [value]="module._id"> {{module.moduleName}}/option> 
    </select> 
    ` 
}) 
export class AwesomeComponent { 

modules: any[]; 
selectedModule: any = null; 

loadModules(){ 
    //load you modules set selectedModule to the on with the 
    //id of modInst.modID[0]._id you can either loop or use .filter to find it. 

    } 
} 

在這裏裝載從JSON模型在組件創建的selectedModule一個變量,設置爲相匹配的ID模塊的價值。在這裏看到這個答案對於如何在選擇輸入使用ngModel一個例子:

Binding select element to object in Angular 2

而且selectedModule會,如果你需要啓用/禁用輸入等基於選擇反映當前所選項目的價值。

Plunker example

[值]工作,因爲原來的問題是使用多個/串ID。但是,如果您想使用其他類型,例如對象,您應該使用[ngValue]。

+0

哎呀,這很有意義!沒有意識到選擇元素的結合是如此簡單...我做到了,所以當'toggleEditing'函數被觸發時,它將selectedValue設置爲xD哇,非常感謝! –

+0

這不符合預期。在這種情況下,'selectedModule'將等於所選選項的值=>模塊的ID,而不是模塊對象本身,當你想要完整的對象時,它會打破所有的事情,唯一的辦法是我可以自動預選一個選項是當[ngValue](不是[值],只能用於字符串或數字)是與「selectedModule」相同的對象。 – mp3por

+0

@ mp3por我添加了一個工作plunker。值與字符串和數字一樣工作原來的問題,我也更新了答案,以表明你是否在使用其他任何東西,比如你需要使用的對象[ngValue]。 – kmcnamee