0

I am trying to send the select value to the javascript, however I am receiving "undefined".

Example:

this._foos = [
{Name:'Foo1', Value: 1},
{Name:'Foo2', Value: 2},
{Name:'Foo3', Value: 3},
{Name:'Foo4', Value: 4}
]

I am using *ngFor to display a dropdownlist options.

I would now like to send the Value to the component, however I am unable to figure out how.

Html:

<select [(ngModel)]="foo" name="foo" class="form-control" (change)="selectFoo(foo.Value)">
 <option *ngFor="let foo of _foos">{{foo.Name}}</option>
</select>

Js:

I have tried the following using the (change) event:

 selectFoo(fooVal: any) { // any - is replaced by actual Object type in actual code
        // get supp obj from list
        console.log(fooVal); // it is undefined
    } 
Harry
  • 3,031
  • 7
  • 42
  • 67
  • is this a duplicae? did you checked [this answer](https://stackoverflow.com/questions/34686855/angular2-access-a-select-event-change-within-the-component) – Ermir Beqiraj Nov 26 '17 at 19:00

2 Answers2

0

you have to bind a value to the [value] property binding

<select [(ngModel)]="fooValue" name="foo" class="form-control" (change)="selectFoo(fooValue)">
 <option *ngFor="let foo of _foos" [value]="foo.Name" >{{foo.Name}}</option>
</select>

Demo

El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37
  • thanks, it works. can you elaborate a little more as to why I need to do that? I thought the ngModel was binding it already – Harry Nov 26 '17 at 18:56
0

you are printing the 'foo' object but you are passing the 'fooVal' parameter.

console.log(fooVal);

will work fine

Amr Alaa
  • 545
  • 3
  • 7