如何将 jQuery 导入 Angular2 TypeScript 项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39511788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:13:03  来源:igfitidea点击:

How to import jQuery to Angular2 TypeScript projects?

jqueryangulartypescriptangular2-directivestypescript-typings

提问by smartmouse

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

typings install dt~jquery --save --global

So now i have jqueryfolder under typings/globalfolder in my project directory. In addition the following new line has been added to my typings.jsonfile:

所以现在我在我的项目目录中的jquery文件夹下有文件typings/global夹。此外,以下新行已添加到我的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-modulefile) but I do not know how to correctly import jQuery library. Here is my source file:

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

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?

但我不能使用$nor jQuery。你下一步怎么做?

回答by Chinmay

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

准备好使用 $!

回答by Sheo Sagar

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.

现在它将起作用。

回答by user1089766

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;

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

回答by rinukkusu

You could also load your jQuery Javascript file in a normal scripttag in the headsection of your index.html.

您还可以scriptheadindex.html 部分的普通标签中加载您的 jQuery Javascript 文件。

<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 所需的变量,因为您将没有所需的所有插件的类型:

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

declare var $: any;

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

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

回答by vidalsasoon

You should have a typings.json that points to your jquery typing file. Then:

你应该有一个指向你的 jquery 输入文件的 Typings.json。然后:

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.

然后像往常一样使用 $ 。

回答by Abhinandan

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.

我认为在 angular 2 中使用 jquery 应该不是问题。如果正确安装了 jquery 的类型和依赖项,那么在 angular 2 中使用 jquery 应该不是问题。

I was able to use jquery in my angular 2 project with proper installation. And by proper installation, I mean the installation of jquery typings in order to recognize it in typescript.

通过正确安装,我能够在我的 angular 2 项目中使用 jquery。通过正确安装,我的意思是安装 jquery 类型以便在打字稿中识别它。

After that, I was able to use jquery in following way:

之后,我可以通过以下方式使用 jquery:

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

回答by V.Tran

This is old question and there're some answers already. However existing answers are overly complicated ( answer from user1089766 contains many unnecessary stuffs). Hope this helps someone new.

这是个老问题,已经有一些答案了。然而,现有的答案过于复杂(来自 user1089766 的答案包含许多不必要的东西)。希望这可以帮助新人。

Add <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>Into your index.htmlfile.

添加 <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. Let say you want to use inside a component name ExperimentComponent then:

现在@Inject(jQueryToken)可以使用了。假设您想在组件名称 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 时,警报函数都会调用并弹出消息。