简体   繁体   English

如何将jQuery导入Angular2 TypeScript项目?

[英]How to import jQuery to Angular2 TypeScript projects?

I want to wrap some jQuery code in an Angular2 directive. 我想在Angular2指令中包含一些jQuery代码。

I installed jQuery library for Typings into my project with the following command: 我使用以下命令将Typings的jQuery库安装到我的项目中:

typings install dt~jquery --save --global

So now i have jquery folder under typings/global folder in my project directory. 所以现在我的项目目录中的typings/global文件夹下有jquery文件夹。 In addition the following new line has been added to my typings.json file: 此外,我的typings.json文件中添加了以下新行:

{
    "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. 我开始编写一个新的Angular2指令(我导入到app-module文件中),但我不知道如何正确导入jQuery库。 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 . 但我不能使用也不是$ jQuery What is the next step? 你下一步怎么做?

Step 1: get jquery in your project 第1步:在项目中获取jquery

npm install jquery

Step 2: add type for jquery 第2步:为jquery添加类型

npm install -D @types/jquery

Step 3: Use it in your component! 第3步:在组件中使用它!

import * as $ from 'jquery';

Ready to use $! 准备使用$!

If you are using "@angular/cli" then install: 如果您使用“@ angular / cli”,请安装:

npm install jquery --save

Second step install: 第二步安装:

install: npm install @types/jquery --save-dev

And find your file name in "angular-cli.json" on the root and add the inside of as like: 并在根目录下的“angular-cli.json”中找到您的文件名,并添加如下内容:

script:["../node_modules/jquery/dist/jquery.min.js"]

Now it will work. 现在它会起作用。

jQuery.service.ts jQuery.service.ts

 import { OpaqueToken } from '@angular/core'
export let JQ_TOKEN = new OpaqueToken('jQuery');

index.ts` index.ts`

export * from './jQuery.service';

app.module.ts app.module.ts

declare let jQuery : Object;

@NgModule({
  providers: [
    { provide: TOASTR_TOKEN, useValue: toastr },
    { provide: JQ_TOKEN, useValue: jQuery },
})
export class AppModule { }

how to use Jquery in component 如何在组件中使用Jquery

   import { Component, Input, ViewChild, ElementRef, Inject } from '@angular/core'
import { JQ_TOKEN } from './jQuery.service'

@Component({
  selector: 'simple-modal',
  template: `
  <div id="{{elementId}}" #modalcontainer class="modal fade" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
          <h4 class="modal-title">{{title}}</h4>
        </div>
        <div class="modal-body" (click)="closeModal()">
          <ng-content></ng-content>
        </div>
      </div>
    </div>
  </div>
  `,
  styles: [`
    .modal-body { height: 250px; overflow-y: scroll; }
  `]
})
export class SimpleModalComponent {
  @Input() title: string;
  @Input() elementId: string;
  @Input() closeOnBodyClick: string;
  @ViewChild('modalcontainer') containerEl: ElementRef;

  constructor(@Inject(JQ_TOKEN) private $: any) {}

  closeModal() {
    if(this.closeOnBodyClick.toLocaleLowerCase() === "true") {
      this.$(this.containerEl.nativeElement).modal('hide');
    }
  }
}

You should have a typings.json that points to your jquery typing file. 你应该有一个typings.json指向你的jquery输入文件。 Then: 然后:

systemjs.config (notice map setting for jquery) systemjs.config(jquery的通知映射设置)

System.config({
    defaultJSExtensions: true,
    paths: {
        // paths serve as alias
        'npm:': 'node_modules/'
    },
    map: {
        'app':  'app',
        jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js',
        material: 'npm:material-design-lite/dist/material.min.js',

        // angular bundles
        '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
        ....
    },
    packages: {
        app: { main: 'main', format: 'register', defaultExtension: 'js' },
        'rxjs': { defaultExtension: 'js' }
    },
});

In component: 在组件中:

import $ from 'jquery';

Then use $ as usual. 然后像往常一样使用$。

You could also load your jQuery Javascript file in a normal script tag in the head section of your index.html. 您还可以将您的jQuery Javascript文件加载到index.html的head部分中的普通script标记中。

<html>
    <head>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" />
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.js" />

        ...
    </head>
    ...

Then in the component or directive where you need it, just declare the $ variable needed for jQuery, since you won't have the typings for all the plugins you need: 然后在您需要它的组件或指令中,只需声明jQuery所需的$ variable,因为您不需要所有所需插件的输入:

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

declare var $: any;

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

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

I don't think it should be a issue to use jquery with angular 2. If the typings and the dependencies for jquery are installed properly, then it should not be a issue to use jquery in angular 2. 我不认为使用带有角度2的jquery应该是一个问题。如果正确安装了jquery的类型和依赖关系,那么在角度2中使用jquery应该不是问题。

I was able to use jquery in my angular 2 project with proper installation. 我能够在我的角度2项目中使用jquery并正确安装。 And by proper installation, I mean the installation of jquery typings in order to recognize it in typescript. 通过正确的安装,我的意思是安装jquery类型,以便在打字稿中识别它。

After that, I was able to use jquery in following way: 之后,我能够以下列方式使用jquery:

jQuery(document).ready({
    ()=>{
        alert("Hello!");
    };
});

This is old question and there're some answers already. 这是一个古老的问题,已经有了一些答案。 However existing answers are overly complicated ( answer from user1089766 contains many unnecessary stuffs). 但是现有的答案过于复杂(来自user1089766的回答包含许多不必要的东西)。 Hope this helps someone new. 希望这有助于新人。

Add <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script> Into your index.html file. <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>index.html文件中。

Create jQuery.Service.ts: 创建jQuery.Service.ts:

import {InjectionToken} from "@angular/core";
export let jQueryToken = new InjectionToken('jQuery'); 

In you module file, add this jQueryToken to provider: 在您的模块文件中,将此jQueryToken添加到提供程序:

providers:[
{
    provide: jQueryToken,
    useValue: jQuery

}] 

Now @Inject(jQueryToken) and it is ready to use. 现在@Inject(jQueryToken) ,它已准备好使用。 Let say you want to use inside a component name ExperimentComponent then: 假设您想在组件名称ExperimentComponent中使用,然后:

import {Component, Inject, OnInit} from '@angular/core';
import {jQueryToken} from "./common/jquery.service";

@Component({
    selector: 'app-experiment',
    templateUrl: './experiment.component.html',
    styleUrls: ['./experiment.component.css']
})
export class ExperimentComponent implements OnInit {

    constructor(@Inject(jQueryToken) private $: any) {
        $(document).ready(function () {
            alert(' jQuery is working');
        });
    }

    ngOnInit() {
    }

}

Whenever you open ExperimentComponent the alert function will call and pop up the message. 每当您打开ExperimentComponent时,警报功能都会调用并弹出消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM