2016-01-22 70 views
8

我想在表單中使用<select>以讓用戶能夠更新不同<option>之間的值。我在這裏使用了指南中的技術:https://angular.io/docs/ts/latest/guide/forms.html。這是我講的樣品:它要求從myApp.services的updateOrder()Angular 2:如何從表單的不同選項中獲取選定的值?

<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()。

我的問題是當我試圖將數據從表單發送到後端:<input>的所有部分都可以,但不是那些與<select>(它返回原始值,而不是所選的一個)。

有沒有人遇到過這樣或類似的問題? 感謝您的幫助!

+0

看起來像一個dup http://stackoverflow.com/questions/34686855/angular2-access-a-select-event-change-within-the-component –

回答

20

有一種方法可以從不同的選項中獲取值。 檢查這個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; 
    } 
1

其實我不能重現你的問題。我用inputselect以非常簡單的形式創建了一個plunkr。當我提交表單時,我在綁定對象中有實際值。看到這個plunkr:https://plnkr.co/edit/5C3agW7QZfcrdt88QzSh?p=preview

隨意告訴我,如果我沒有正確理解你的問題。

Thierry

+0

其實,似乎你已經轉載我的問題在你的plunkr:當我嘗試提交表單時,我在''內獲得了正確的值,但無論我在'