11

I have to pass the value of the option whenever the item is selected.But after my event takes place, the passed value is always undefined. My code is as follows :

<select (change)="handle(this.value);">
<option value="0">Addition</option>
<option value="1">Subtraction</option>
<option value="2">Multiplication</option>
<option value="3">Division</option>
</select>

My angular2 code is as follows:

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  n1 = 0;
 n2 = 0;
 result = 0;

handle(value){
  alert("selected option's value is "+value);
}

constructor() { }
  ngOnInit() {

 }

} 

The problem is that whenever there is any change of option, the parameter(value) which is passed to the handle function is always "undefined".

alert("selected option's value is "+value);

In this line, the value of the parameter "value" is always undefined.

Please help!

Thanks in advance!

Sai Raman Kilambi
  • 878
  • 2
  • 12
  • 29
  • Possible duplicate of [How can I get new selection in "select" in Angular 2?](https://stackoverflow.com/questions/33700266/how-can-i-get-new-selection-in-select-in-angular-2) – anoop Jun 21 '17 at 15:01

3 Answers3

18

try with template reference variable

<select (change)="handle(selectField.value);" #selectField>
Yordan Nikolov
  • 2,598
  • 13
  • 16
  • Thanks! You solved my problem. Can you explain why do I need to use a local variable ? – Sai Raman Kilambi Jun 21 '17 at 15:06
  • 1
    A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component. More info: https://angular.io/guide/template-syntax#template-reference-variables--var- – Yordan Nikolov Jun 21 '17 at 15:09
3

Try to use this approach:

HTML TEMPLATE

<select [(ngModel)]="selectedValue" (change)="handle();">
 <option [ngValue]="0">Addition</option>
 <option [ngValue]="1">Subtraction</option>
 <option [ngValue]="2">Multiplication</option>
 <option [ngValue]="3">Division</option>
</select>

HomeComponent COMPONENT

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

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
    selectedValue: number;
    n1 = 0;
    n2 = 0;
    result = 0;

    handle() {
        alert("selected option's value is " + this.selectedValue);
    }

    constructor() {}
    ngOnInit() {

    }
}
rick dana
  • 92
  • 1
  • 8
  • 1
    This looks like an overkill when we have to the option of passing values as part of the event handler method signature. – Tarik Dec 14 '17 at 18:34
3

Consider also

<select (change)="handle($event.target.value);">
Miguel Carvalhais Matos
  • 1,113
  • 2
  • 13
  • 21