Angular 2:如何从表单的不同选项中获取所选值?

Yan*_*rel 11 forms html-select angular-ngmodel angular2-forms angular

我想<select>在表单中使用a 让用户能够更新不同的值<option>.我使用了指南中的技术:https://angular.io/docs/ts/latest/guide/forms.html.这是我正在谈论的样本:

<div class="form-group">
    <label for="type">Type :</label>
    <select class="form-control" [(ngModel)]="order.type" ngControl="type">
        <option *ngFor="#type of types" [value]="type">{{type}}</option>
    </select>
</div>
Run Code Online (Sandbox Code Playgroud)

在我的order-details.component中,我有一个updateOrder(),它从myApp.services调用updateOrder().

我的问题是当我尝试将数据从表单发送到后端时:所有具有a的部分<input>都可以,但不是那些<select>(它返回原始值,而不是选择的那个).

有没有人遇到过这个或类似的问题?谢谢你的帮助!

Mub*_*hir 23

有一种方法可以从不同的选项中获取价值.检查这个plunker

component.html

 <select class="form-control" #t (change)="callType(t.value)">
      <option *ngFor="#type of types" [value]="type">{{type}}</option>
    </select>
Run Code Online (Sandbox Code Playgroud)

component.ts

this.types = [ 'type1', 'type2', 'type3' ];
   this.order = {
      type: 'type1'          
  };  

  callType(value){
    console.log(value);
    this.order.type=value;
  }
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 5

解决这个问题几个小时了。

检查(不完整)文档以在NgSelectOption页面中找到一个名为“ngValue”的项目

不确定这是否是预期用途,但它似乎工作正常。

所以而不是使用

[value]="item"
Run Code Online (Sandbox Code Playgroud)

用:

[ngValue]="item"
Run Code Online (Sandbox Code Playgroud)

如果您想在更改时执行某些操作,只需在 select 和 ngModelChange 事件上使用 ngModel。