Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to use a <select> in a form to let the user being able to update values among different <option>. I have used the technique from the guide here: https://angular.io/docs/ts/latest/guide/forms.html. Here is the sample I am talking about:

<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>

In my order-details.component I have got an updateOrder() which calls the updateOrder() from myApp.services.

My problem is when I am trying to send the data from the form to the back-end: all the parts with an <input> are OK, but not those with <select> (it returns the original values, and not the one selected).

Does anyone have encountered this or a similar problem? Thanks for your help!

like image 302
Yannick Morel Avatar asked Jan 22 '16 15:01

Yannick Morel


People also ask

What the selector option does in angular?

What is a Selector in Angular? A selector is one of the properties of the object that we use along with the component configuration. A selector is used to identify each component uniquely into the component tree, and it also defines how the current component is represented in the HTML DOM.


2 Answers

There is a way to get the value from different options. check this 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;
  }
like image 189
Mubashir Avatar answered Oct 11 '22 14:10

Mubashir


Been tackling this problem for a few hours.

Checked in the (incomplete) documentation to find an item in the NgSelectOption page called "ngValue"

Not sure if this is the intended use but it seemed to work fine.

So instead of using

[value]="item"

Use:

[ngValue]="item"

Just use ngModel on the select and ngModelChange event if you want to do something when it changes.

like image 40
Jason Avatar answered Oct 11 '22 13:10

Jason