2016-07-30 226 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