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

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

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


当前回答

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

步骤1:在index.html文件中引用jquery cdn

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

步骤2:假设我们想在点击按钮时显示或隐藏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>

步骤3:在下面的组件文件中,import声明$如下所示:

declare var $: any;

然后创建如下函数:

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

它将与最新的Angular和JQuery一起工作

其他回答

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

在模板我有例如:

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

EDIT

代替使用:

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

use

declare var $: any;

在index.html中输入:

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

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

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

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

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

此外,Angular2类型版本的角量角器与jQuery $有问题,所以顶部接受的答案没有给我一个干净的编译。

以下是我开始工作的步骤:

index . 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);

    }
}

你也可以尝试用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();
    }
}

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