How to import jQuery to Angular2 TypeScript projects?

smartmouse picture smartmouse · Sep 15, 2016 · Viewed 41.3k times · Source

I want to wrap some jQuery code in an Angular2 directive.

I installed jQuery library for Typings into my project with the following command:

typings install dt~jquery --save --global

So now i have jquery folder under typings/global folder in my project directory. In addition the following new line has been added to my typings.json file:

{
    "globalDependencies": {
        "core-js": "registry:dt/core-js#0.0.0+20160602141332",
        "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
        "node": "registry:dt/node#6.0.0+20160807145350",
        "jquery": "registry:dt/jquery#1.10.0+20160908203239"
    }
}

I started to write a new Angular2 directive (that I imported into app-module file) but I do not know how to correctly import jQuery library. Here is my source file:

import {Directive} from '@angular/core';

@Directive({
    selector: "my-first-directive"
})

export class MyFirstDirective {
    constructor() {
        $(document).ready(function () {
            alert("Hello World");
        });
    }
}

But I can't use nor $ nor jQuery. What is the next step?

Answer

Chinmay picture Chinmay · Apr 12, 2017

Step 1: get jquery in your project

npm install jquery

Step 2: add type for jquery

npm install -D @types/jquery

Step 3: Use it in your component!

import * as $ from 'jquery';

Ready to use $!