Angular 2从Jquery调用Typescript函数会导致未捕获的TypeError

Angular 2从Jquery调用Typescript函数会导致未捕获的TypeError,jquery,angularjs,typescript,angular,Jquery,Angularjs,Typescript,Angular,我有一个带有输入文本字段的组件,我使用JQuery将输入事件侦听器附加到该组件。当输入值改变时,我想调用一个Typescript函数,但它会抛出一个未捕获的TypeError 这是我的密码: import {Component, Input, Output, EventEmitter, ElementRef, OnInit} from 'angular2/core'; declare var jQuery: any; @Component({ selector: 'setting-pr

我有一个带有输入文本字段的组件,我使用JQuery将输入事件侦听器附加到该组件。当输入值改变时,我想调用一个Typescript函数,但它会抛出一个未捕获的TypeError

这是我的密码:

import {Component, Input, Output, EventEmitter, ElementRef, OnInit} from 'angular2/core';
declare var jQuery: any;

@Component({
    selector: 'setting-priority',
    template: '<input [(ngModel)]="priority" class="setting-priority" type="text">'
})

export class SettingPriorityComponent implements OnInit{
    @Input() priority: number;
    @Output() prioChanged: EventEmitter<number> = new EventEmitter();

    constructor(private elementRef:ElementRef) { }

    ngOnInit() {
        jQuery(this.elementRef.nativeElement).find('input').on('input', function() {
            // Here I will pass the changed value to onChange function
            this.onChange();
        });
    }

    ngOnChanges(changes) { 
        this.prioChanged.emit(this.priority);
    }

    // In this function I will receive the value and assign it to the priority variable
    onChange() {
        console.log("onchange!");
    }
}
import{Component,Input,Output,EventEmitter,ElementRef,OnInit}来自'angular2/core';
声明var jQuery:any;
@组成部分({
选择器:“设置优先级”,
模板:“”
})
导出类设置PriorityComponent在NIT上实现{
@输入()优先级:数字;
@Output()prioChanged:EventEmitter=neweventemitter();
构造函数(私有elementRef:elementRef){}
恩戈尼尼特(){
jQuery(this.elementRef.nativeElement).find('input').on('input',function()){
//在这里,我将把更改后的值传递给onChange函数
this.onChange();
});
}
ngOnChanges(更改){
this.prioChanged.emit(this.priority);
}
//在此函数中,我将接收值并将其分配给优先级变量
onChange(){
log(“onchange!”);
}
}
我使用Jquery是因为输入值将以编程方式设置——在本例中,Angular的更改检测无法工作

当我触发输入事件时,我收到一个未捕获类型错误:this.onChange不是一个函数


我做错了什么?

我会使用箭头功能。通过这种方式,您可以使用词法This(对应于组件实例):

有关更多详细信息,请参阅此链接:
尽量避免在Angular2中使用jQuery

获取元素引用的更具角度的方法是

@Component({
    selector: 'setting-priority',
    template: '<input #prio [(ngModel)]="priority" class="setting-priority" type="text">'
})
export class SettingPriorityComponent implements OnInit{
  @ViewChild('prio') priority;

  ngOnInit() {
    console.log(this.priority);
  }
}
@组件({
选择器:“设置优先级”,
模板:“”
})
导出类设置PriorityComponent在NIT上实现{
@ViewChild(“prio”)优先级;
恩戈尼尼特(){
console.log(this.priority);
}
}
但要添加事件处理程序,您只需要:

template: '<input [(ngModel)]="priority" (input)="onChange()" class="setting-priority" type="text">'
模板:“”

效果很好!非常感谢。顺便说一下,我找到了另一种方法——将JavaScript变量绑定到angular上下文,然后使用它调用函数:
var self=this
jQuery(this.elementRef.nativeElement).find('input').on('input',函数{self.onChange();})谢谢!我使用jQueryUI通过拖放来创建一个可排序的表,因为我没有为原生Angular 2找到如此简单的解决方案。
template: '<input [(ngModel)]="priority" (input)="onChange()" class="setting-priority" type="text">'