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

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

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


当前回答

我跳过jquery的安装,因为在我之前创建的所有帖子中都提到了这一点。因此,您已经安装了jquery。像这样将t导入组件

import * as $ from 'jquery';

将工作,但还有另一种“angular”的方式来做到这一点,即创建一个服务。

一步不。1:创建jquery.service.ts文件。

// in Angular v2 it is OpaqueToken (I am on Angular v5)
import { InjectionToken } from '@angular/core';
export const JQUERY_TOKEN = new InjectionToken('jQuery');

的一步。不。2:在app.module.ts中注册服务

import { JQUERY_TOKEN } from './services/jQuery.service';
declare const jQuery: Object;

providers: [
    { provide: JQUERY_TOKEN, useValue: jQuery },
]

一步不。3:将服务注入到组件my-super-duper.component.ts中

import { Component, Inject } from '@angular/core';

export class MySuperDuperComponent {
    constructor(@Inject(JQUERY_TOKEN) private $: any) {}

    someEventHandler() {
        this.$('#my-element').css('display', 'none');
    }
}

如果有人能解释这两种方法的优缺点,我将非常感激:DI jquery as a service vs. import * as $ from 'jquery';

其他回答

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

npm install jquery — save

其次,进入。/angular-cli。在你的Angular CLI项目文件夹的根目录下找到script:[]属性,并包括jQuery的路径,如下所示:

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

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

import * as $ from 'jquery';
(or)
declare var $: any;

看看下面使用jQuery在点击时动画div的代码,特别是在第二行。我们正在从jQuery导入所有的$。

import { Component, OnInit  } from '@angular/core';
import * as $ from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Look jQuery Animation working in action!';

  public ngOnInit()
  {
    $(document).ready(function(){
        $("button").click(function(){
            var div = $("div");  
            div.animate({left: '100px'}, "slow");
            div.animate({fontSize: '5em'}, "slow");
        });
    });
  }
}

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

此外,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);

    }
}

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

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

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

我跳过jquery的安装,因为在我之前创建的所有帖子中都提到了这一点。因此,您已经安装了jquery。像这样将t导入组件

import * as $ from 'jquery';

将工作,但还有另一种“angular”的方式来做到这一点,即创建一个服务。

一步不。1:创建jquery.service.ts文件。

// in Angular v2 it is OpaqueToken (I am on Angular v5)
import { InjectionToken } from '@angular/core';
export const JQUERY_TOKEN = new InjectionToken('jQuery');

的一步。不。2:在app.module.ts中注册服务

import { JQUERY_TOKEN } from './services/jQuery.service';
declare const jQuery: Object;

providers: [
    { provide: JQUERY_TOKEN, useValue: jQuery },
]

一步不。3:将服务注入到组件my-super-duper.component.ts中

import { Component, Inject } from '@angular/core';

export class MySuperDuperComponent {
    constructor(@Inject(JQUERY_TOKEN) private $: any) {}

    someEventHandler() {
        this.$('#my-element').css('display', 'none');
    }
}

如果有人能解释这两种方法的优缺点,我将非常感激:DI jquery as a service vs. import * as $ from 'jquery';

使用Angular Cli

 npm install jquery --save

在角。脚本下的Json数组

"scripts": [ "node_modules/jquery/dist/jquery.min.js" ] // copy relative path of node_modules>jquery>dist>jquery.min.js to avoid path error

现在要使用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');
}