如何将jQuery导入Angular2 TypeScript项目? [英] How to import jQuery to Angular2 TypeScript projects?

查看:110
本文介绍了如何将jQuery导入Angular2 TypeScript项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Angular2指令中包装一些jQuery代码.

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

我使用以下命令将用于打字的jQuery库安装到我的项目中:

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

typings install dt~jquery --save --global

所以现在我在项目目录的typings/global文件夹下有jquery文件夹.此外,以下新行已添加到我的typings.json文件中:

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"
    }
}

我开始编写新的Angular2指令(已将其导入到app-module文件中),但我不知道如何正确导入jQuery库.这是我的源文件:

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");
        });
    }
}

但是我既不能使用$也不能使用jQuery.下一步是什么?

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

推荐答案

步骤1:在项目中获取jquery

npm install jquery

步骤2:为jquery添加类型

npm install -D @types/jquery

第3步:在您的组件中使用它!

import * as $ from 'jquery';

可以使用$!

这篇关于如何将jQuery导入Angular2 TypeScript项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆