Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

angular - How to import jQuery to Angular2 TypeScript projects?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 $!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...