【问题标题】:Angular 2 calling a Typescript function from Jquery causes uncaught TypeErrorAngular 2 从 Jquery 调用 Typescript 函数会导致未捕获的 TypeError
【发布时间】:2016-09-04 14:19:31
【问题描述】:

我有一个带有输入文本字段的组件,我使用 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!");
    }
}

我正在使用 Jquery,因为输入值将以编程方式设置 - 在这种情况下,Angular 的更改检测不起作用Details here

当我触发输入事件时,我收到 Uncaught TypeError: this.onChange is not a function

我做错了什么?

【问题讨论】:

    标签: jquery angularjs typescript angular


    【解决方案1】:

    我会使用箭头函数。这样你就可以使用词法 this(对应于组件实例):

    jQuery(this.elementRef.nativeElement).find('input').on('input', () => {
      this.onChange();
    });
    

    查看此链接了解更多详情: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    【讨论】:

    • 效果很好!谢谢!顺便说一句,我找到了另一种方法 - 将 JavaScript 变量绑定到角度上下文,然后使用它调用函数:var self = this;jQuery(this.elementRef.nativeElement).find('input').on('input', function { self.onChange(); });
    【解决方案2】:

    尽量避免在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);
      }
    }
    

    但要添加事件处理程序,您只需要:

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

    【讨论】:

    • 谢谢!我正在使用 Jquery-UI 使用拖放操作使表格可排序,因为我没有为原生 Angular 2 找到如此简单的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多