【问题标题】:angular 2 select options default valueangular 2 选择选项默认值
【发布时间】:2016-07-30 22:15:04
【问题描述】:

我似乎不知道如何轻松地将一个值设置为选择下拉列表的默认值。

我当前的代码

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

我尝试过使用 [selected] 装饰器,但不知道如何让它工作。

假设我在下面有这个 modInst json 对象:

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

我希望从所有模块中选择 modInst.modID[0]._id。_id(模块)是填充选择列表的内容

有什么简单的方法吗?

编辑:

我尝试添加[selected]="module._id == modInst.modID[0]._id",但我没有成功将其设为选定值

我也试过[ngValue]="modInst.modID[0]._id",但它仍然没有选择列表中id为6的模块

最后一个添加...我尝试了手动“选择”,但加载时仍然没有选择值[selected]="module._id == '7'"

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用 [(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

    [value] 有效,因为原始问题使用数字/字符串 id。但是,如果您想使用其他类型,例如对象,您应该使用 [ngValue]。

    【讨论】:

    • 啊,这太有意义了!没有意识到对 select 元素的投标就这么简单......我这样做了,所以当“toggleEditing”功能被触发时,它会将 selectedValue 设置为 id xD 哇非常感谢!
    • 这不能按预期工作。在这种情况下,“selectedModule”将等于所选选项的值 => 模块的 ID。不是模块对象本身。当你想要完整的对象时,这会破坏一切。我可以让它自动预选的唯一方法一个选项是 [ngValue](不是只能与字符串或数字一起使用的 [value])与“selectedModule”相同的对象。
    • @mp3por 我添加了一个工作插件。 value 与原始问题中的字符串和数字一样。我还更新了答案以说明您是否正在使用其他任何东西,例如您需要使用 [ngValue] 的对象。