Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing parameters on change event in angular 2

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!

like image 573
Sai Raman Kilambi Avatar asked Jun 21 '17 14:06

Sai Raman Kilambi


2 Answers

try with template reference variable

<select (change)="handle(selectField.value);" #selectField>
like image 139
Yordan Nikolov Avatar answered Sep 21 '22 09:09

Yordan Nikolov


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

    }
}
like image 29
rick dana Avatar answered Sep 18 '22 09:09

rick dana