如何在 Angular 中使用 jQuery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30623825/
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 16:42:41  来源:igfitidea点击:

How to use jQuery with Angular?

jqueryangular

提问by Waog

Can anyone tell me, how to use jQuerywith Angular?

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

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

I'm aware there are workarounds like manipulating the classor idof the DOM element upfront, but I'm hoping for a cleaner way of doing it.

我知道有一些变通方法,比如预先操作DOM 元素的id,但我希望有一种更简洁的方法来做到这一点。

采纳答案by werenskjold

Using jQuery from Angular2 is a breeze compared to ng1. If you are using TypeScript you could first reference jQuery typescript definition.

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

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

TypescriptDefinitions are not required since you could just use anyas the type for $or jQuery

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

In your angular component you should reference a DOM element from the template using @ViewChild()After the view has been initialized you can use the nativeElementproperty of this object and pass to jQuery.

在你的 angular 组件中,你应该使用模板中的 DOM 元素@ViewChild()在视图初始化之后你可以使用nativeElement这个对象的属性并传递给 jQuery。

Declaring $(or jQuery) as JQueryStatic will give you a typed reference to 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);

This example is available on plunker: http://plnkr.co/edit/Nq9LnK?p=preview

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

tslint will complain about chosennot being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file

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

interface JQuery {
    chosen(options?:any):JQuery;
}    

回答by Starwave

Why is everyone making it a rocket science? For anyone else who needs to do some basic stuff on static elements, for example, bodytag, just do this:

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

  1. In index.html add scripttag with the path to your jquery lib, doesn't matter where (this way you can also use IE conditional tags to load lower version of jquery for IE9 and less).
  2. In your export componentblock have a function that calls your code: $("body").addClass("done");Normaly this causes declaration error, so just after all imports in this .ts file, add declare var $:any;and you are good to go!
  1. 在 index.html 中添加script带有 jquery lib 路径的标签,在哪里都没有关系(这样你也可以使用 IE 条件标签来加载 IE9 及更低版本的 jquery)。
  2. 在您的export component块中有一个调用您的代码的函数:$("body").addClass("done");通常这会导致声明错误,因此在此 .ts 文件中的所有导入之后,添加declare var $:any;即可!

回答by Akash

This is what worked for me.

这对我有用。

STEP 1 - First things first

第 1 步 - 第一件事

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

STEP 2 - IMPORT

第 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();

#UPDATE - Feb - 2017

#更新 - Feb - 2017

Lately, I'm writing code with ES6instead of typescriptand am able to importwithout * as $in the import statement. This is what it looks like now:

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

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

Good Luck.

祝你好运。

回答by Devesh Jadon

Now it has become very easy, You can do it by simply declaring jQuery variable with any type inside Angular2 controller.

现在它变得非常容易,您可以通过简单地在 Angular2 控制器中声明任何类型的 jQuery 变量来完成。

declare var jQuery:any;

Add this just after import statements and before component decorator.

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

To access any element with id X or Class X you just have to do

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

jQuery("#X or .X").someFunc();

回答by Yosam Lee

A simple way:

一个简单的方法:

1. include script

1.包含脚本

index.html

索引.html

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

2. declare

2. 申报

my.component.ts

my.component.ts

declare var $: any;

3. use

3.使用

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

回答by AmanDeepSharma

Please follow these simple steps. It worked for me. Lets start with a new angular 2 app to avoid any confusion. I'm using Angular cli. So, install it if you don't have it already. https://cli.angular.io/

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

Step 1: Create a demo angular 2 app

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

ng new jquery-demo

you can use any name. Now check if it is working by running below cmd.(Now, make sure that you are pointing to 'jquery-demo' if not use cd command )

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

ng serve

you will see "app works!" on browser.

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

Step 2: Install Bower (A package manager for the web)

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

Run this command on cli (make sure that you are pointing to 'jquery-demo' if not use cd command ):

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

npm i -g bower --save

Now after successful installation of bower, Create a 'bower.json' file by using below command:

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

bower init

It will ask for inputs, just press enter for all if you want default values and at the end type "Yes" when it'll ask "Looks good?"

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

Now you can see a new file (bower.json) in folder "jquery-demo". You can find more info on https://bower.io/

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

Step 3: Install jquery

第三步:安装jquery

Run this command

运行这个命令

bower install jquery --save

It will create a new folder (bower_components) which will contain jquery installation folder. Now you have jquery installed in 'bower_components' folder.

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

Step 4: Add jquery location in 'angular-cli.json' file

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

Open 'angular-cli.json' file (present in 'jquery-demo' folder) and add jquery location in "scripts". It will look like this:

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

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

Step 5: Write simple jquery code for testing

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

Open 'app.component.html' file and add a simple code line, The file will look like this:

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

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

Now Open 'app.component.ts' file and add jquery variable declaration and code for 'p' tag. You should use lifecycle hook ngAfterViewInit() also. After making changes the file will look like this:

现在打开'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();
             });
           });
     }
}

Now run your angular 2 app by using 'ng serve' command and test it. It should work.

现在使用“ng serve”命令运行您的 angular 2 应用程序并对其进行测试。它应该工作。

回答by Mourad Zouabi

You can implement the lifecycle hook ngAfterViewInit()to add some DOM manipulations

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

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

Be careful when using router because angular2 may recycle views .. so you have to be sure that the DOM elements manipulations are done only in the first call of afterViewInit .. ( You can use static boolean variables to do so )

使用路由器时要小心,因为 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;
        }
    }
}

回答by Kamil Kie?czewski

I do it in simpler way - first install jquery by npm in console: npm install jquery -Sand then in component file I just write: let $ = require('.../jquery.min.js')and it works! Here full example from some my code:

我用更简单的方式来做 - 首先在控制台中通过 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});
      ...
    }
}

In teplate I have for instance:

例如,在 teplate 中,我有:

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


EDIT

编辑

Alternatively instead of using:

或者,而不是使用:

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

use

declare var $: any;

and in your index.html put:

并在您的 index.html 中输入:

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

This will initialize jquery only once globaly - this is important for instance for use modal windows in bootstrap...

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

回答by Laxmikanta Nayak

step 1: use the command : npm install jquery --save

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

step 2: you can simply import angular as :

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

import $ from 'jquery';

从'jquery'导入$;

that's all .

就这样 。

An example would be :

一个例子是:

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


}

回答by Jahal

If you use angular-cli you can do :

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

  1. Install the dependency:

    npm install jquery --save

    npm install @types/jquery --save-dev

  2. Import the file:

    Add "../node_modules/jquery/dist/jquery.min.js" to the "script" section in .angular-cli.json file

  3. Declare jquery:

    Add "$" to the "types" section of tsconfig.app.json

  1. 安装依赖

    npm 安装 jquery --save

    npm install @types/jquery --save-dev

  2. 导入文件

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

  3. 声明 jquery

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

You can find more details on official angular cli doc

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