有人能告诉我,如何在Angular中使用jQuery吗?

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

我知道有一些变通办法,比如在前面操纵DOM元素的类或id,但我希望有一种更干净的方式来做到这一点。


当前回答

请遵循这些简单的步骤。这对我很管用。为了避免混淆,让我们从一个新的angular 2应用开始。我使用的是Angular cli。因此,如果您还没有安装它,请安装它。 https://cli.angular.io/

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

ng new jquery-demo

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

ng serve

你会在浏览器上看到“app works!”

步骤2:安装Bower (web包管理器)

在cli下运行这个命令(如果不使用cd命令,请确保你指向的是'jquery-demo'):

npm i -g bower --save

现在在成功安装凉亭后,创建一个“凉亭”。Json文件,使用以下命令:

bower init

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

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

步骤3:安装jquery

执行此命令

bower install jquery --save

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

第四步:在angular-cli中添加jquery location。json的文件

“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'文件,并添加jquery变量声明和'p'标签的代码。你也应该使用生命周期钩子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应用并测试它。它应该会起作用。

其他回答

只写

declare var $:any;

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

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

这对我很有效

与ng1相比,在Angular2中使用jQuery非常简单。如果你使用的是TypeScript,你可以先引用jQuery TypeScript定义。

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

TypescriptDefinitions不是必需的,因为你可以使用任何类型作为$或jQuery的类型

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

将$(或jQuery)声明为querystatic将为您提供对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会抱怨选择不是$上的属性,为了解决这个问题,你可以在自定义的*.d中添加一个定义到JQuery接口。ts文件

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

请遵循这些简单的步骤。这对我很管用。为了避免混淆,让我们从一个新的angular 2应用开始。我使用的是Angular cli。因此,如果您还没有安装它,请安装它。 https://cli.angular.io/

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

ng new jquery-demo

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

ng serve

你会在浏览器上看到“app works!”

步骤2:安装Bower (web包管理器)

在cli下运行这个命令(如果不使用cd命令,请确保你指向的是'jquery-demo'):

npm i -g bower --save

现在在成功安装凉亭后,创建一个“凉亭”。Json文件,使用以下命令:

bower init

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

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

步骤3:安装jquery

执行此命令

bower install jquery --save

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

第四步:在angular-cli中添加jquery location。json的文件

“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'文件,并添加jquery变量声明和'p'标签的代码。你也应该使用生命周期钩子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应用并测试它。它应该会起作用。

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

declare var jQuery:any;

将其添加在import语句之后和组件装饰符之前。

要访问任何id为X或类为X的元素,你只需要这样做

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

第一步:使用命令: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'));
  }


}