【问题标题】:Angular 2: How to get the selected value from different options of a form?Angular 2:如何从表单的不同选项中获取选定的值?
【发布时间】:2016-04-29 06:10:24
【问题描述】:

我想在表单中使用<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>

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

我的问题是当我尝试将数据从表单发送到后端时:所有带有 &lt;input&gt; 的部分都可以,但不是带有 &lt;select&gt; 的部分(它返回原始值,而不是被选中的那个)。

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

【问题讨论】:

标签: forms html-select angular angular-ngmodel angular2-forms


【解决方案1】:

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

component.html

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

组件.ts

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

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

【讨论】:

    【解决方案2】:

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

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

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

    所以不要使用

    [value]="item"
    

    用途:

    [ngValue]="item"
    

    如果您想在它发生变化时执行某些操作,只需在 select 和 ngModelChange 事件上使用 ngModel。

    【讨论】:

    • ngValue 可以引用一个对象,而 value 只能引用一个原始值。例如,如果在这种情况下“项目”是一个对象,并且选项标签是 {{item.name}},那么您可以执行 &lt;select size="10" [(ngModel)]="this.selected"&gt; &lt;option *ngFor="let item of items" [ngValue]="item"&gt;{{item.Name}}&lt;/option&gt; &lt;/select&gt; 在这种情况下 this.selected 将是一个对象。如果你只使用[value],this.selected 将是一个名为'{object, object}'的字符串
    【解决方案3】:

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

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

    蒂埃里

    【讨论】:

    • 实际上,您似乎在 plunkr 中重现了我的问题:当我尝试提交您的表单时,我在 &lt;input&gt; 中得到了正确的值,但无论我在&lt;select&gt;,控制台日志显示“type1”。你没有同样的行为吗?顺便感谢您花时间重现问题:)
    • 穆巴希尔现在已经解决了我的问题,但感谢您的宝贵时间!
    【解决方案4】:

    如果您有如下所示的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2015-05-09
      • 2020-03-23
      • 2016-09-13
      相关资源
      最近更新 更多