Abhijith Nagaraja
Abhijith Nagaraja

Reputation: 3380

Using JavaScript in typescript with JQuery

I am trying to use a 3rd party library (autonumeric) with Typescript + Angular2.

I have tried the following

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

and on init I am trying to use it.

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

But when I compile, I am getting the following error.

error TS2339: Property 'autoNumeric' does not exist on type 'JQuery'

I am not getting where I am going wrong. Any help would be appreciated

NOTE

I have included the autonumeric.js in the index.html

Upvotes: 0

Views: 637

Answers (2)

TGH
TGH

Reputation: 39248

In my case I just kept it simple and declared jQuery as an 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'});
    }
}

Here is the full example: http://www.syntaxsuccess.com/viewarticle/using-jquery-with-angular-2.0

Upvotes: 1

kemsky
kemsky

Reputation: 15261

I did it exactly like you and it works fine. You should create definition file to extend JQuery interface and add reference to *.d.ts file to main.ts:

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

where declarations.d.ts contains:

declare interface JQuery {
    autoNumeric: any;
}

Upvotes: 1

Related Questions