388

谁能告诉我,如何将jQueryAngular一起使用?

class MyComponent {
    constructor() {
        // how to query the DOM element from here?
    }
}

我知道有一些解决方法,比如预先操作 DOM 元素的id,但我希望有一种更简洁的方法。

4

25 回答 25

354

与 ng1 相比,使用 Angular2 中的 jQuery 轻而易举。如果您使用的是 TypeScript,您可以首先参考 jQuery typescript 定义。

tsd install jquery --save
or
typings install dt~jquery --global --save

TypescriptDefinitions 不是必需的,因为您可以将any其用作$or的类型jQuery

在您的角度组件中,您应该使用模板中的 DOM 元素来引用@ViewChild()视图初始化后,您可以使用nativeElement该对象的属性并传递给 jQuery。

$将(或)声明jQuery为 JQueryStatic 将为您提供对 jQuery 的类型化引用。

import {bootstrap}    from '@angular/platform-browser-dynamic';
import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
declare var $:JQueryStatic;

@Component({
    selector: 'ng-chosen',
    template: `<select #selectElem>
        <option *ngFor="#item of items" [value]="item" [selected]="item === selectedValue">{{item}} option</option>
        </select>
        <h4> {{selectedValue}}</h4>`
})
export class NgChosenComponent implements AfterViewInit {
    @ViewChild('selectElem') el:ElementRef;
    items = ['First', 'Second', 'Third'];
    selectedValue = 'Second';

    ngAfterViewInit() {
        $(this.el.nativeElement)
            .chosen()
            .on('change', (e, args) => {
                this.selectedValue = args.selected;
            });
    }
}

bootstrap(NgChosenComponent);

此示例可在 plunker 上找到:http ://plnkr.co/edit/Nq9LnK?p=preview

tslint 将抱怨chosen不是 $ 上的属性,要解决此问题,您可以在自定义 *.d.ts 文件中向 JQuery 接口添加定义

interface JQuery {
    chosen(options?:any):JQuery;
}    
于 2015-06-05T09:16:33.117 回答
137

这对我有用。

第 1 步 - 首先要做的事

// In the console
// First install jQuery
npm install --save jquery
// and jQuery Definition
npm install -D @types/jquery

第 2 步 - 导入

// Now, within any of the app files (ES2015 style)
import * as $ from 'jquery';
//
$('#elemId').width();

// OR

// CommonJS style - working with "require"
import $ = require('jquery')
//
$('#elemId').width();

#更新 -Feb - 2017

最近,我正在编写代码,ES6而不是在. 这就是它现在的样子:typescriptimport* as $import statement

import $ from 'jquery';
//
$('#elemId').width();

祝你好运。

于 2016-11-01T07:22:56.720 回答
128

为什么每个人都把它变成一门火箭科学?body对于需要对静态元素(例如标签)做一些基本操作的其他人,只需执行以下操作:

  1. 在 index.html 中添加script带有 jquery lib 路径的标签,在哪里都没有关系(这样你也可以使用 IE 条件标签为 IE9 和更低版本加载较低版本的 jquery)。
  2. 在你的export component块中有一个调用你的代码的函数:$("body").addClass("done");通常这会导致声明错误,所以在这个 .ts 文件中的所有导入之后,添加declare var $:any;并且你很高兴!
于 2016-07-07T12:58:29.107 回答
59

现在它变得非常简单,您可以通过简单地在 Angular2 控制器中使用任何类型声明 jQuery 变量来实现。

declare var jQuery:any;

在 import 语句之后和组件装饰器之前添加它。

要访问具有 id X 或 Class X 的任何元素,您只需要做

jQuery("#X or .X").someFunc();
于 2016-07-08T16:41:15.513 回答
32

一个简单的方法:

1.包含脚本

索引.html

<script type="text/javascript" src="assets/js/jquery-2.1.1.min.js"></script>

2. 申报

我的.component.ts

declare var $: any;

3.使用

@Component({
  selector: 'home',
  templateUrl: './my.component.html',
})
export class MyComponent implements OnInit {
 ...
  $("#myselector").style="display: none;";
}
于 2017-06-22T07:01:35.237 回答
27

请按照这些简单的步骤。它对我有用。让我们从一个新的 angular 2 应用程序开始,以避免任何混淆。我正在使用 Angular cli。因此,如果您还没有它,请安装它。 https://cli.angular.io/

第 1 步:创建一个演示 Angular 2 应用程序

ng new jquery-demo

您可以使用任何名称。现在通过在 cmd 下运行来检查它是否正常工作。(现在,如果不使用 cd 命令,请确保您指向“jquery-demo”)

ng serve

您将看到“应用程序有效!” 在浏览器上。

第 2 步:安装 Bower(网络包管理器)

在 cli 上运行此命令(如果不使用 cd 命令,请确保您指向“jquery-demo”):

npm i -g bower --save

现在在成功安装 bower 后,使用以下命令创建一个“bower.json”文件:

bower init

它会要求输入,如果您想要默认值,只需按 Enter 键,最后键入“是”,当它会询问“看起来不错?”

现在您可以在文件夹“jquery-demo”中看到一个新文件 (bower.json)。您可以在https://bower.io/上找到更多信息

第三步:安装jquery

运行此命令

bower install jquery --save

它将创建一个包含 jquery 安装文件夹的新文件夹 (bower_components)。现在您已将 jquery 安装在“bower_components”文件夹中。

第 4 步:在 'angular-cli.json' 文件中添加 jquery 位置

打开“angular-cli.json”文件(存在于“jquery-demo”文件夹中)并在“脚本”中添加 jquery 位置。它看起来像这样:

"scripts": ["../bower_components/jquery/dist/jquery.min.js"
              ]

第 5 步:编写简单的 jquery 代码进行测试

打开 'app.component.html' 文件并添加一个简单的代码行,该文件将如下所示:

<h1>
  {{title}}
</h1>
<p>If you click on me, I will disappear.</p>

现在打开“app.component.ts”文件并为“p”标签添加 jquery 变量声明和代码。您还应该使用生命周期挂钩 ngAfterViewInit()。进行更改后,文件将如下所示:

import { Component, AfterViewInit } from '@angular/core';
declare var $:any;

@Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css']
})
export class AppComponent {
     title = 'app works!';

     ngAfterViewInit(){
           $(document).ready(function(){
             $("p").click(function(){
             $(this).hide();
             });
           });
     }
}

现在使用 'ng serve' 命令运行 Angular 2 应用程序并对其进行测试。它应该工作。

于 2017-02-17T10:28:37.333 回答
22

使用 Angular CLI

 npm install jquery --save

在scripts数组下的angular.json中

"scripts": [ "node_modules/jquery/dist/jquery.min.js" ] // copy relative path of node_modules>jquery>dist>jquery.min.js to avoid path error

现在要使用 jQuery,您所要做的就是在您想使用 jQuery 的任何组件中按如下方式导入它。

例如在根组件中导入和使用 jQuery

import { Component, OnInit  } from '@angular/core';
import * as $ from 'jquery'; // I faced issue in using jquery's popover
Or
declare var $: any; // declaring jquery in this way solved the problem

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


ngOnInit() {
}

jQueryExampleModal() { // to show a modal with dummyId
   $('#dummyId').modal('show');
}
于 2019-04-28T06:19:15.043 回答
13

你可以实现生命周期钩子ngAfterViewInit()来添加一些 DOM 操作

ngAfterViewInit() {
            var el:any = elelemtRef.domElement.children[0];
            $(el).chosen().on('change', (e, args) => {
                _this.selectedValue = args.selected;
            });
}

使用路由器时要小心,因为 angular2 可能会回收视图..所以您必须确保仅在第一次调用 afterViewInit 时完成 DOM 元素操作..(您可以使用静态布尔变量来执行此操作)

class Component {
    let static chosenInitialized  : boolean = false;
    ngAfterViewInit() {
        if (!Component.chosenInitialized) {
            var el:any = elelemtRef.domElement.children[0];
            $(el).chosen().on('change', (e, args) => {
                _this.selectedValue = args.selected;
            });
            Component.chosenInitialized = true;
        }
    }
}
于 2015-10-04T18:45:56.230 回答
13

如果您使用 angular-cli,您可以执行以下操作:

  1. 安装依赖

    npm install jquery --save

    npm install @types/jquery --save-dev

  2. 导入文件

    将“../node_modules/jquery/dist/jquery.min.js”添加到 .angular-cli.json 文件的“脚本”部分

  3. 声明 jquery

    将“$”添加到 tsconfig.app.json 的“类型”部分

您可以在官方 Angular cli 文档中找到更多详细信息

于 2017-08-09T09:28:49.880 回答
13

第 1 步:使用命令:npm install jquery --save

第 2 步:您可以简单地将 angular 导入为:

从'jquery'导入$;

就这样 。

一个例子是:

import { Component } from '@angular/core';
import  $ from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  constructor(){
    console.log($('body'));
  }


}
于 2017-10-09T11:55:22.477 回答
12

我以更简单的方式来做 - 首先在控制台中通过 npm 安装 jquery:npm install jquery -S然后在组件文件中我只写:let $ = require('.../jquery.min.js')它可以工作!这是我的一些代码的完整示例:

import { Component, Input, ElementRef, OnInit } from '@angular/core';
let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');

@Component({
    selector: 'departments-connections-graph',
    templateUrl: './departmentsConnectionsGraph.template.html',
})

export class DepartmentsConnectionsGraph implements OnInit {
    rootNode : any;
    container: any;

    constructor(rootNode: ElementRef) {
      this.rootNode = rootNode; 
    }

    ngOnInit() {
      this.container = $(this.rootNode.nativeElement).find('.departments-connections-graph')[0];
      console.log({ container : this.container});
      ...
    }
}

在 teplate 我有例如:

<div class="departments-connections-graph">something...</div>

编辑

或者,而不是使用:

let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');

采用

declare var $: any;

并在您的 index.html 中放置:

<script src="assets/js/jquery-2.1.1.js"></script>

这将仅在全局初始化一次 jquery - 这对于例如在引导程序中使用模式窗口很重要......

于 2016-06-29T12:37:25.300 回答
10

//安装jquerynpm install jquery --save

//为jquery安装类型定义typings install dt~jquery --global --save

//按照指定将jquery库添加到构建配置文件中(在“angular-cli-build.js”文件中)

vendorNpmFiles: [
  .........
  .........
  'jquery/dist/jquery.min.js'
]

//运行构建以在构建中添加jquery库 ng build

//添加相对路径配置(在system-config.js中) /** Map relative paths to URLs. */ const map: any = { ....., ......., 'jquery': 'vendor/jquery/dist' };

/** User packages configuration. */
const packages: any = {
......,
'jquery':{ main: 'jquery.min',
format: 'global',
defaultExtension: 'js'}};

//在你的组件文件中导入jquery库

import 'jquery';

下面是我的示例组件的代码片段

import { Component } from '@angular/core';
import 'jquery';
@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',  
  styleUrls: ['app.component.css']
})
export class AppComponent {
  list:Array<number> = [90,98,56,90];
  title = 'app works!';
  isNumber:boolean = jQuery.isNumeric(89)  
  constructor(){}
}
于 2016-08-12T14:31:23.840 回答
8

在 Angular2 中使用 Jquery(4)

遵循这些设置

安装 Jquery 和 Juqry 类型定义

用于 Jquery 安装npm install jquery --save

对于 Jquery 类型定义安装 npm install @types/jquery --save-dev

然后只需导入 jquery

import { Component } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent { 
  console.log($(window)); // jquery is accessible 
}
于 2017-06-09T14:52:36.823 回答
5

首先,使用 npm 安装 jQuery,如下所示:

npm install jquery — save

其次,转到 Angular CLI 项目文件夹根目录下的 ./angular-cli.json 文件,找到 scripts: [] 属性,并包含 jQuery 的路径,如下所示:

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

现在,要使用 jQuery,您所要做的就是将它导入到您想要使用 jQuery 的任何组件中。

import * as $ from 'jquery';
(or)
declare var $: any;

看看下面的代码,它使用 jQuery 在点击时为 div 设置动画,尤其是在第二行。我们从 jQuery 将所有内容都作为 $ 导入。

import { Component, OnInit  } from '@angular/core';
import * as $ from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Look jQuery Animation working in action!';

  public ngOnInit()
  {
    $(document).ready(function(){
        $("button").click(function(){
            var div = $("div");  
            div.animate({left: '100px'}, "slow");
            div.animate({fontSize: '5em'}, "slow");
        });
    });
  }
}
于 2019-12-31T07:05:46.850 回答
4

由于我是个笨蛋,我认为有一些工作代码会很好。

此外, Angular2 类型版本的angular-protractor 与 jQuery 有问题 $,所以最受接受的答案并没有给我一个干净的编译。

以下是我必须工作的步骤:

索引.html

<head>
...
    <script   src="https://code.jquery.com/jquery-3.1.1.min.js"   integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
...
</head>

在 my.component.ts 里面

import {
    Component,
    EventEmitter,
    Input,
    OnInit,
    Output,
    NgZone,
    AfterContentChecked,
    ElementRef,
    ViewChild
} from "@angular/core";
import {Router} from "@angular/router";

declare var jQuery:any;

@Component({
    moduleId: module.id,
    selector: 'mycomponent',
    templateUrl: 'my.component.html',
    styleUrls: ['../../scss/my.component.css'],
})
export class MyComponent implements OnInit, AfterContentChecked{
...
    scrollLeft() {

        jQuery('#myElement').animate({scrollLeft: 100}, 500);

    }
}
于 2016-10-03T22:39:45.073 回答
4

写吧

declare var $:any;

在所有导入部分之后,您可以使用 jQuery 并将 jQuery 库包含在您的 index.html 页面中

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

它对我有用

于 2016-10-15T11:20:53.807 回答
3

我正在跳过 jquery 的安装,因为在我之前创建的所有帖子中都提到了这一点。因此,您已经安装了 jquery。像这样将 t 导入到您的组件中

import * as $ from 'jquery';

会起作用,但是通过创建服务还有另一种“角度”的方式来做到这一点。

步号 1:创建jquery.service.ts 文件

// in Angular v2 it is OpaqueToken (I am on Angular v5)
import { InjectionToken } from '@angular/core';
export const JQUERY_TOKEN = new InjectionToken('jQuery');

步。不。2:在app.module.ts中注册服务

import { JQUERY_TOKEN } from './services/jQuery.service';
declare const jQuery: Object;

providers: [
    { provide: JQUERY_TOKEN, useValue: jQuery },
]

步号 3:将服务注入您的组件my-super-duper.component.ts

import { Component, Inject } from '@angular/core';

export class MySuperDuperComponent {
    constructor(@Inject(JQUERY_TOKEN) private $: any) {}

    someEventHandler() {
        this.$('#my-element').css('display', 'none');
    }
}

如果有人能解释这两种方法的优缺点,我将不胜感激:DI jquery as a service vs. import * as $ from 'jquery';

于 2018-04-21T21:14:54.537 回答
3

其他人已经发过了。但我在这里举一个简单的例子,这样可以帮助一些新人。

第 1 步:在您的 index.html 文件中引用 jquery cdn

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

步骤 2:假设我们想在单击按钮时显示 div 或隐藏 div:

 <input type="button" value="Add New" (click)="ShowForm();">


 <div class="container">
  //-----.HideMe{display:none;} is a css class----//

  <div id="PriceForm" class="HideMe">
     <app-pricedetails></app-pricedetails>
  </div>
  <app-pricemng></app-pricemng>
 </div>

Step-3:在组件文件下面的 import 中声明 $ 如下:

declare var $: any;

而不是像下面这样创建函数:

 ShowForm(){
   $('#PriceForm').removeClass('HideMe');
 }

它将与最新的 Angular 和 JQuery 一起使用

于 2019-05-06T21:30:28.177 回答
3

角 12

npm i jquery

这个很重要 :npm i @types/jquery

角.json

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

.ts 文件

import * as $ from "jquery";
于 2021-10-04T19:06:29.657 回答
2


1) 访问组件中的 DOM。

import {BrowserDomAdapter } from '@angular/platform-browser/src/browser/browser_adapter';
constructor(el: ElementRef,public zone:NgZone) {
     this.el = el.nativeElement;
     this.dom = new BrowserDomAdapter();
 }
 ngOnInit() {
   this.dom.setValue(this.el,"Adding some content from ngOnInit"); 
 }

您可以通过以下方式包含 jQuery。2)在加载angular2之前将jquery文件包含在index.html中

      <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- jquery file -->
    <script src="js/jquery-2.0.3.min.js"></script>
    <script src="js/jquery-ui.js"></script>
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

您可以通过以下方式使用 Jquery,这里我使用的是 JQuery Ui 日期选择器。

    import { Directive, ElementRef} from '@angular/core';
    declare  var $:any;
    @Directive({
      selector: '[uiDatePicker]',
     })
    export class UiDatePickerDirective {
      private el: HTMLElement;
      constructor(el: ElementRef) {
        this.el = el.nativeElement;

     }

    ngOnInit() {
        $(this.el).datepicker({
         onSelect: function(dateText:string) {
            //do something on select
         }
        });
    }
}

这对我有用。

于 2016-06-07T13:16:49.603 回答
2

全局库安装作为官方文档在这里

  1. 从 npm 安装:

    npm install jquery --save

  2. 将所需的脚本文件添加到脚本中:

    "scripts": [ "node_modules/jquery/dist/jquery.slim.js" ],

如果您正在运行它,请重新启动服务器,它应该可以在您的应用程序上运行。


如果您想在单个组件内使用import $ from 'jquery';,请在组件内使用

于 2018-09-30T12:22:23.963 回答
1

我发现最有效的方法是在页面/组件构造函数中使用时间为 0 的 setTimeout。这让 jQuery 在 Angular 完成加载所有子组件后的下一个执行周期中运行。可以使用其他一些组件方法,但我尝试过的所有方法在 setTimeout 内运行时效果最佳。

export class HomePage {
    constructor() {
        setTimeout(() => {
            // run jQuery stuff here
        }, 0);
    }
}
于 2016-04-06T13:56:31.510 回答
1

这对我有用 - Angular 2 with webpack

我尝试声明$为类型any,但每当我尝试使用任何 JQuery 模块时,我得到的(例如)$(..).datepicker()不是一个函数

由于我的 vendor.ts 文件中包含了 Jquery,因此我只需使用

import * as $ from 'jquery';

我现在可以使用 Jquery 插件(如 bootstrap-datetimepicker)

于 2017-05-03T07:05:30.863 回答
1

您也可以尝试使用“InjectionToken”导入它。如此处所述:在没有类型定义的情况下在 Angular/Typescript 中使用 jQuery

您可以简单地注入 jQuery 全局实例并使用它。为此,您将不需要任何类型定义或类型。

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

export const JQ_TOKEN = new InjectionToken('jQuery');

export function jQueryFactory() {
    return window['jQuery'];
}

export const JQUERY_PROVIDER = [
    { provide: JQ_TOKEN, useFactory: jQueryFactory },
];

在您的 app.module.ts 中正确设置时:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

import { JQ_TOKEN } from './jQuery.service';

declare let jQuery: Object;

@NgModule({
    imports: [
        BrowserModule
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        { provide: JQ_TOKEN, useValue: jQuery }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

您可以开始在组件中使用它:

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

@Component({
    selector: "selector",
    templateUrl: 'somefile.html'
})
export class SomeComponent {
    constructor( @Inject(JQ_TOKEN) private $: any) { }

    somefunction() {
        this.$('...').doSomething();
    }
}
于 2017-05-16T14:54:56.170 回答
-1

安装 jquery

终端$npm install jquery

(对于引导程序 4...)

终端$npm install popper.js

终端$npm install bootstrap

然后将import语句添加到app.module.ts.

import 'jquery'

(对于引导程序 4...)

import 'popper.js'
import 'bootstrap'

现在您将不再需要<SCRIPT>标记来引用 JavaScript。

(您要使用的任何 CSS 仍然必须在 中引用styles.css

@import "~bootstrap/dist/css/bootstrap.min.css";
于 2018-09-19T00:37:33.027 回答