如何在Angular中使用jQuery?

Wao*_*aog 321 jquery angular

谁能告诉我,如何使用jQuery的

class MyComponent {
    constructor() {
        // how to query the DOM element from here?
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道有一些变通方法可以预先操作DOM元素的id,但是我希望有一种更简洁的方法.

wer*_*old 318

与ng1相比,使用Angular2中的jQuery是一件轻而易举的事.如果您使用的是TypeScript,则可以首先引用jQuery typescript定义.

tsd install jquery --save
or
typings install dt~jquery --global --save
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

这个例子可以在plunker上找到:http://plnkr.co/edit/Nq9LnK?p = preview

tslint会抱怨chosen不是$上的属性,为了解决这个问题,你可以在自定义*.d.ts文件中为JQuery接口添加一个定义

interface JQuery {
    chosen(options?:any):JQuery;
}    
Run Code Online (Sandbox Code Playgroud)

  • 这并不难设置,但与角度1相比,它肯定不是"轻而易举".在角度1中你不需要做任何事情,你可以在任何地方使用jquery.angular 1构建在jquery之上. (17认同)
  • 在通过打字安装定义之后,JQueryStatic仍然无法识别. (8认同)
  • 在alpha37 https://github.com/angular/angular/blob/2.0.0-alpha.37/CHANGELOG.md核心中添加了新的回调:添加了afterContentInit,afterViewInit和afterViewChecked hooks(d49bc43),关闭#3897 (7认同)
  • 我认为我们需要对此进行更新,因为现在我们使用NPM进行打字 (4认同)
  • 我不确定为什么需要`setTimeout`解决方法.我已尝试过其他几个jQuery组件,似乎所有这些组件都需要这种解决方法才能正确初始化.我希望这将在将来的ng2版本中发生变化 (2认同)
  • `npm install @ types/jquery --save` (2认同)

Sta*_*ave 121

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

  1. 在index.html中添加script带有jquery lib路径的标记,无论在哪里(这样你也可以使用IE条件标记为IE9加载较低版本的jquery等等).
  2. 在你的export component块中有一个调用你的代码的函数:$("body").addClass("done");Normaly这会导致声明错误,所以在这个.ts文件中的所有导入之后,添加declare var $:any;并且你很高兴!

  • 对我不起作用.所以我要学习一些火箭科学.:) (15认同)
  • 角度2的目的是消除处理DOM的复杂性.Angular 2有一个diff算法,可以为你有效地渲染你的组件,这就是为什么它更好地欺骗jquery它通过将DOM指向角度2组件来操纵DOM,而不是直接操纵DOM. (11认同)
  • `声明var $:any;`获胜! (5认同)
  • intellisense,我的朋友,这就是原因 (4认同)
  • 这绝对有效,但如果你不再生活在石器时代,那就去找一下接受的答案吧. (2认同)

Aka*_*ash 101

这对我有用.

第1步 - 首先要做的事情

// In the console
// First install jQuery
npm install --save jquery
// and jQuery Definition
npm install -D @types/jquery
Run Code Online (Sandbox Code Playgroud)

第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();
Run Code Online (Sandbox Code Playgroud)

#UPDATE - Feb - 2017

最近,我正在写代码ES6,而不是typescript和我能够import* as $import statement.这就是现在的样子:

import $ from 'jquery';
//
$('#elemId').width();
Run Code Online (Sandbox Code Playgroud)

祝好运.

  • 花了我一个小时来弄清楚如何将jQuery放入Angular 2(正确)......非常确定Web开发正在倒退. (45认同)
  • 在 **app.module.ts** 中导入 * as $ from 'jquery';` 以使其可用于整个项目。顺便说一句:[“为什么 --save 而不是 --save-dev?”](https://github.com/Microsoft/types-publisher/issues/81) (3认同)
  • `import $ from'jquery';`这是本页imo上最漂亮的jquery import语句.正是我希望它看起来像. (3认同)
  • @Starboy 那是因为你不应该在 Angular 应用程序中需要任何 JQuery,如果你这样做,你很可能做错了什么。 (3认同)

Dev*_*don 52

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

declare var jQuery:any;
Run Code Online (Sandbox Code Playgroud)

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

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

jQuery("#X or .X").someFunc();
Run Code Online (Sandbox Code Playgroud)


小智 27

一个简单的方法:

包括脚本

的index.html

<script type="text/javascript" src="assets/js/jquery-2.1.1.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

宣布

my.component.ts

declare var $: any;
Run Code Online (Sandbox Code Playgroud)

3.使用

@Component({
  selector: 'home',
  templateUrl: './my.component.html',
})
export class MyComponent implements OnInit {
 ...
  $("#myselector").style="display: none;";
}
Run Code Online (Sandbox Code Playgroud)


Ama*_*rma 23

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

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

ng new jquery-demo
Run Code Online (Sandbox Code Playgroud)

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

ng serve
Run Code Online (Sandbox Code Playgroud)

你会看到"app works!" 在浏览器上.

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

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

npm i -g bower --save
Run Code Online (Sandbox Code Playgroud)

现在成功安装了凉亭后,使用以下命令创建'bower.json'文件:

bower init
Run Code Online (Sandbox Code Playgroud)

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

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

第3步:安装jquery

运行此命令

bower install jquery --save
Run Code Online (Sandbox Code Playgroud)

它将创建一个包含jquery安装文件夹的新文件夹(bower_components).现在你在'bower_components'文件夹中安装了jquery.

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

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

"scripts": ["../bower_components/jquery/dist/jquery.min.js"
              ]
Run Code Online (Sandbox Code Playgroud)

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

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

<h1>
  {{title}}
</h1>
<p>If you click on me, I will disappear.</p>
Run Code Online (Sandbox Code Playgroud)

现在打开'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();
             });
           });
     }
}
Run Code Online (Sandbox Code Playgroud)

现在使用'ng serve'命令运行你的angular 2 app并测试它.它应该工作.

  • 使用npm设置不是更容易吗?`npm install jquery --save`,然后``scripts':["../ node_modules/jquery/dist/jquery.js"]`,然后`'从$ jquery'中导入$;`在*.ts文件中.使用凉亭有什么好处? (3认同)
  • 恕我直言.这是我仍然使用bower进行客户端依赖的最佳方法. (2认同)

var*_*yal 21

使用 Angular Cli

 npm install jquery --save
Run Code Online (Sandbox Code Playgroud)

在脚本数组下的 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
Run Code Online (Sandbox Code Playgroud)

现在要使用 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');
}
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用命令安装`@types/jquery`:`npm i --save-dev @types/jquery`并将`"types": ["jquery"]`添加到文件`tsconfig.app.json`或 `compilerOptions` 下的 `tsconfig.lib.json` ,这样就完全省略了 `declare var $: any;` 语句 (2认同)

Mou*_*abi 13

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

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

使用路由器时要小心,因为angular2可能会回收视图..所以你必须确保DOM元素操作只在afterViewInit的第一次调用中完成..(你可以使用静态布尔变量来做到这一点)

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • ElementRef`类型中不存在`属性'domElement' (3认同)

Kam*_*ski 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});
      ...
    }
}
Run Code Online (Sandbox Code Playgroud)

在teplate我有例如:

<div class="departments-connections-graph">something...</div>
Run Code Online (Sandbox Code Playgroud)

编辑

或者代替使用:

let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
Run Code Online (Sandbox Code Playgroud)

使用

declare var $: any;
Run Code Online (Sandbox Code Playgroud)

并在你的index.html中:

<script src="assets/js/jquery-2.1.1.js"></script>
Run Code Online (Sandbox Code Playgroud)

这将初始化jquery只有一次全局 - 这对于在bootstrap中使用模态窗口很重要...


小智 11

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

第2步:您可以简单地导入角度为:

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


}
Run Code Online (Sandbox Code Playgroud)


小智 10

//安装jquerynpm install jquery --save

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

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

vendorNpmFiles: [
  .........
  .........
  'jquery/dist/jquery.min.js'
]
Run Code Online (Sandbox Code Playgroud)

//运行构建以在构建中添加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'}};
Run Code Online (Sandbox Code Playgroud)

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

import 'jquery';
Run Code Online (Sandbox Code Playgroud)

下面是我的示例组件的代码snipppet

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(){}
}
Run Code Online (Sandbox Code Playgroud)


小智 10

如果你使用angular-cli,你可以这样做:

  1. 安装依赖项:

    npm install jquery --save

    npm install @ types/jquery --save-dev

  2. 导入文件:

    将"../node_modules/jquery/dist/jquery.min.js"添加到.angular-cli.json文件中的"script"部分

  3. 声明jquery:

    将"$"添加到tsconfig.app.json的"types"部分

您可以在官方角度cli doc上找到更多详细信息


小智 8

在Angular2中使用Jquery(4)

请遵循以下设定

安装Jquery和Juqry类型定义

对于Jquery安装 npm install jquery --save

用于Jquery Type定义安装 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 
}
Run Code Online (Sandbox Code Playgroud)


小智 7

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

\n\n
npm install jquery \xe2\x80\x94 save\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
"scripts": [ "../node_modules/jquery/dist/jquery.min.js" ]\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
import * as $ from \'jquery\';\n(or)\ndeclare var $: any;\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
import { Component, OnInit  } from \'@angular/core\';\nimport * as $ from \'jquery\';\n@Component({\n  selector: \'app-root\',\n  templateUrl: \'./app.component.html\',\n  styleUrls: [\'./app.component.css\']\n})\nexport class AppComponent implements OnInit {\n  title = \'Look jQuery Animation working in action!\';\n\n  public ngOnInit()\n  {\n    $(document).ready(function(){\n        $("button").click(function(){\n            var div = $("div");  \n            div.animate({left: \'100px\'}, "slow");\n            div.animate({fontSize: \'5em\'}, "slow");\n        });\n    });\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n


小智 5

写吧

declare var $:any;
Run Code Online (Sandbox Code Playgroud)

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

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
Run Code Online (Sandbox Code Playgroud)

这对我有用


小智 5

角12

npm i jquery

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

角度.json

"scripts": [
              "node_modules/jquery/dist/jquery.min.js"
            ]
Run Code Online (Sandbox Code Playgroud)

.ts 文件

import * as $ from "jquery";
Run Code Online (Sandbox Code Playgroud)