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

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

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


当前回答

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

export class HomePage {
    constructor() {
        setTimeout(() => {
            // run jQuery stuff here
        }, 0);
    }
}

其他回答

与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;
}    

安装jquery

jquery . jquery . Terminal$ npm

(bootstrap 4…)

终端$ npm安装popper.js

终端$ npm安装引导

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

import 'jquery'

(bootstrap 4…)

import 'popper.js'
import 'bootstrap'

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

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

@import "~bootstrap/dist/css/bootstrap.min.css";

一个简单的方法:

1. 包括脚本

index . html

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

2. 声明

my.component.ts

declare var $: any;

3.使用

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

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

安装依赖项: NPM安装jquery NPM install @types/jquery 导入文件: 在.angular-cli的“script”部分添加“../node_modules/jquery/dist/jquery.min.js”。json文件 jquery: 在tsconfig.app.json的“types”部分添加“$”

你可以在angular cli官方文档中找到更多细节

只写

declare var $:any;

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

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

这对我很有效