在使用JQuery的typescript中使用JavaScript

时间:2016-04-18 22:23:17

标签: jquery typescript angular

我正在尝试使用Typescript + Angular2的第三方库(autonumeric)。

我试过以下

/// <reference path="/typings/main/ambient/jquery/index.d.ts" />
declare interface JQuery {
    autoNumeric: any;
}

并且init我试图使用它。

ngOnInit() {
        $('selector').autoNumeric('init', {options});
    }

但是当我编译时,我收到以下错误。

  

错误TS2339:类型'JQuery'

上不存在属性'autoNumeric'

我没有得到我错的地方。任何帮助将不胜感激

注意

我在index.html中包含了autonumeric.js

2 个答案:

答案 0 :(得分:1)

我做得与你完全一样,而且效果很好。您应该创建定义文件以扩展JQuery接口并将*.d.ts文件的引用添加到main.ts

/// <reference path="./typings/declarations.d.ts" />

declarations.d.ts包含:

declare interface JQuery {
    autoNumeric: any;
}

答案 1 :(得分:1)

在我的情况下,我只是保持简单并将jQuery声明为any

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

@Component({
    selector: 'jquery-integration',
    templateUrl: './components/jquery-integration/jquery-integration.html'
})
export class JqueryIntegration implements OnInit {
    elementRef: ElementRef;
    constructor(elementRef: ElementRef) {
        this.elementRef = elementRef;
    }
    ngOnInit() {
        jQuery(this.elementRef.nativeElement).draggable({containment:'#draggable-parent'});
    }
}

以下是完整示例:http://www.syntaxsuccess.com/viewarticle/using-jquery-with-angular-2.0