Andrew Thomas
Andrew Thomas

Reputation: 2492

Angular 2 issue getting select option value

I have a select

<select name='shape_id' ngModel (change)='changeShape($event.target.value)'>
  <option *ngFor="let shape of shapes" [ngValue]="shape.id">{{shape.name}}</option>
</select>

Here is the data.

  shapes = [
    {id:'1', name:'Angle'},
    {id:'2', name:'Bar'},
   ];

I can't get the value.

 changeShape(shape){
    console.log(shape);
  }

This outputs "0: 1", but I want the value 1.

Here is what the option looks like in inspector.

<option value="0: 1" ng-reflect-ng-value="1">Angle</option>

How do I get the id value 1?

Upvotes: 7

Views: 13522

Answers (2)

Alexander Leonov
Alexander Leonov

Reputation: 4794

You actually don't need to subscribe to 'change' event unless you really want to perform some action when the value changes. But if all you want is to get selected value then it is enough to just bind it to the component property with ngModel.

Component:

import {Component} from '@angular/core';

@Component({
  selector: 'home',
  styleUrls: ['./home.component.css'],
  templateUrl: './home.component.html'
})
export class HomeComponent {

    shapes = [
        {id:'1', name:'Angle'},
        {id:'2', name:'Bar'},
    ];

    shape: string;

    onSelect() {
        // log updated value
        console.log(this.shape);
    }

}

Template:

<select name='shape_id' [(ngModel)]="shape" (change)="onSelect()">
  <option *ngFor="let shape of shapes" [value]="shape.id">{{shape.name}}</option>
</select>

Upvotes: 0

J J B
J J B

Reputation: 9230

Change [ngValue] to [value]

  <select name="shape_id" (change)="changeShape($event.target)">
    <option *ngFor="let shape of shapes" [value]="shape.id">
      {{shape.name}}
    </option>
  </select>

and shape to shape.value.

changeShape(shape){
  console.log(shape.value);
}

Upvotes: 11

Related Questions