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

Angular 2: How to get the selected value from different options of a form?

我想在表单中使用 <select> 让用户能够更新不同 <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>

在我的订单中-details.component 我有一个 updateOrder() 从 myApp.services.

调用 updateOrder()

我的问题是当我尝试将数据从表单发送到后端时:所有带 <input> 的部分都可以,但带 <select> 的部分不行(它 returns 原始值,而不是选择的值)。

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

事实上我无法重现你的问题。我创建了一个带有 inputselect 的非常简单形式的 plunkr。当我提交表单时,绑定对象中有实际值。看到这个 plunkr:https://plnkr.co/edit/5C3agW7QZfcrdt88QzSh?p=preview.

如果我没有正确理解您的问题,请随时告诉我。

蒂埃里

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

component.html

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

component.ts

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

  callType(value){
    console.log(value);
    this.order.type=value;
  }

几个小时以来一直在处理这个问题。

查看(不完整的)文档,在 NgSelectOption 页面中找到一个名为 "ngValue"

的项目

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

所以不用

[value]="item"

使用:

[ngValue]="item"

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

如果您有静态 hard-coded 标签的 select 值,如下所示:

<select #quantity>
  <option value="one">1</option>
  <option value="two">2</option>
  <option value="three">3</option>
  <option value="four">4</option>
  <option value="five">5</option>
</select>

您可以执行以下操作:

@ViewChild('quantity') quantity: ElementRef;

console.log(this.quantity.nativeElement.value);  // will print value of the currently selected option