【问题标题】:passing parameters on change event in angular 2在角度2中传递更改事件的参数
【发布时间】:2017-11-24 13:32:33
【问题描述】:

我必须在选择项目时通过该选项的值。但是在我的事件发生后,传递的值始终是未定义的。我的代码如下:

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

我的angular2代码如下:

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

 }

} 

问题是,无论何时都有任何选项,将传递给句柄函数的参数(值)始终“未定义”。

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

在这一行中,参数“value”的值始终是未定义的。

请帮忙!

提前致谢!

【问题讨论】:

标签: javascript html angular


【解决方案1】:

尝试使用模板引用变量

<select (change)="handle(selectField.value);" #selectField>

【讨论】:

  • 谢谢!你解决了我的问题。你能解释一下为什么我需要使用局部变量吗?
  • 模板引用变量通常是对模板中 DO​​M 元素的引用。它也可以是对 Angular 组件或指令或 Web 组件的引用。更多信息:angular.io/guide/…
【解决方案2】:

尝试使用这种方法:

HTML 模板

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

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

    }
}

【讨论】:

  • 当我们不得不选择将值作为事件处理程序方法签名的一部分传递时,这看起来有点过头了。
【解决方案3】:

同时考虑

<select (change)="handle($event.target.value);">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    相关资源
    最近更新 更多