首页 文章

如何在Angular中使用jQuery?

提问于
浏览
278

任何人都可以告诉我,如何使用 jQueryAngular

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

我知道有一些变通方法可以预先操作DOM元素的类或id,但我希望有一种更清晰的方法 .

21 回答

  • 0

    一个简单的方法:

    1. include script

    的index.html

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

    2. declare

    my.component.ts

    declare var $: any;
    

    3. use

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

    Here is what worked for me - Angular 2 with webpack

    我尝试将 $ 声明为类型 any ,但每当我尝试使用任何JQuery模块时(例如) $(..).datepicker() 都不是函数

    由于我的vendor.ts文件中包含Jquery,因此我只是将其导入到我的组件中

    import * as $ from 'jquery';

    我现在可以使用Jquery插件(如bootstrap-datetimepicker)

  • 1

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

    • Install the dependency

    npm install jquery --save

    npm install @ types / jquery --save-dev

    • Import the file

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

    • Declare jquery

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

    你可以在official angular cli doc找到更多细节

  • 2

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

    在teplate我有例如:

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

    EDIT

    或者代替使用:

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

    使用

    declare var $: any;
    

    并在你的index.html中:

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

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

  • 13

    Global Library Installation as Official documentation here

    • Install from npm:

    npm install jquery --save

    • Add needed script files to scripts:

    "scripts": [ "node_modules/jquery/dist/jquery.slim.js" ],

    如果您正在运行它,请重新启动服务器,它应该在您的应用程序上运行 .


    如果要在单个组件内使用,请在组件内使用 import $ from 'jquery';

  • 1

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

    • 在index.html中添加带有jquery lib路径的 script 标签,无论在哪里(这样你也可以使用IE条件标签为IE9加载较低版本的jquery等等) .

    • export component 块中有一个调用代码的函数: $("body").addClass("done"); Normaly会导致声明错误,所以只需在此.ts文件中的所有导入之后添加 declare var $:any; 就可以了!

  • 1

    请按照这些简单的步骤 . 它对我有用 . 让我们从一个新的角度2应用程序开始,以避免任何混淆 . 我已经拥有它了 . https://cli.angular.io/

    Step 1: Create a demo angular 2 app

    ng new jquery-demo
    

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

    ng serve
    

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

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

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

    npm i -g bower --save
    

    现在成功安装了凉亭后,使用以下命令创建'bower.json'文件:

    bower init
    

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

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

    Step 3: Install jquery

    运行此命令

    bower install jquery --save
    

    它将创建一个包含jquery安装文件夹的新文件夹(bower_components) . 现在你在'bower_components'文件夹中安装了jquery .

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

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

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

    Step 5: Write simple jquery code for testing

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

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

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

    现在使用'ng serve'命令运行你的angular 2 app并测试它 . 它应该工作 .

  • 114

    这对我有用 .

    第1步 - 首先要做的事情

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

    第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 - 2017年2月

    最近,我用 ES6 而不是 typescript 编写代码,并且能够在 import statement 中没有 * as $ import . 这就是现在的样子:

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

    祝好运 .

  • 291

    写吧

    declare var $:any;
    

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

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

    它对我有用

  • 9

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

    第2步:您可以简单地导入角度为:

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

    //安装jquery npm install jquery --save

    //为jquery typings install dt~jquery --global --save 安装类型定义

    //将jquery库添加到指定的构建配置文件中(在“angular-cli-build.js”文件中)

    vendorNpmFiles: [
      .........
      .........
      'jquery/dist/jquery.min.js'
    ]
    

    //运行构建以在构建中添加jquery库 ng build

    //添加相对路径配置(在system-config.js中) /** Map relative paths to URLs. */ const map: any = { ....., ......., 'jquery': 'vendor/jquery/dist' };

    /** User packages configuration. */
    const packages: any = {
    ......,
    'jquery':{ main: 'jquery.min',
    format: 'global',
    defaultExtension: 'js'}};
    

    //导入组件文件中的jquery库

    import 'jquery';
    

    下面是我的示例组件的代码snipppet

    import { Component } from '@angular/core';
    import 'jquery';
    @Component({
      moduleId: module.id,
      selector: 'app-root',
      templateUrl: 'app.component.html',  
      styleUrls: ['app.component.css']
    })
    export class AppComponent {
      list:Array<number> = [90,98,56,90];
      title = 'app works!';
      isNumber:boolean = jQuery.isNumeric(89)  
      constructor(){}
    }
    
  • 2

    我找到的最有效的方法是在页面/组件构造函数中使用时间为0的setTimeout . 这让我们在Angular完成加载所有子组件之后的下一个执行周期中运行jQuery . 可以使用其他一些组件方法,但我在setTimeout内运行时尝试的效果最好 .

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

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

    declare var jQuery:any;
    

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

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

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

    由于我是个笨蛋,我认为有一些工作代码会很好 .

    另外,Angular2打字版本angular-protractor has issues with the 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);
    
        }
    }
    
  • 10

    您可以实现生命周期钩子 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;
            }
        }
    }
    
  • 8

    与ng1相比,使用Angular2中的jQuery是一件轻而易举的事 . 如果您使用的是TypeScript,则可以首先引用jQuery typescript定义 .

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

    TypescriptDefinitions不是必需的,因为您可以使用 any 作为 $jQuery 的类型

    在角度组件中,您应该使用 @ViewChild() 从模板引用DOM元素 . 在初始化视图之后,您可以使用此对象的 nativeElement 属性并传递给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);
    

    这个例子在plunker上可用:http://plnkr.co/edit/Nq9LnK?p=preview

    tslint会抱怨 chosen 不是$上的属性,为了解决这个问题,你可以在自定义* .d.ts文件中为JQuery接口添加一个定义

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

    1)访问组件中的DOM .

    import {BrowserDomAdapter } from '@angular/platform-browser/src/browser/browser_adapter';
    constructor(el: ElementRef,public zone:NgZone) {
         this.el = el.nativeElement;
         this.dom = new BrowserDomAdapter();
     }
     ngOnInit() {
       this.dom.setValue(this.el,"Adding some content from ngOnInit"); 
     }
    

    您可以通过以下方式包含jQuery . 2)在angular2加载之前在index.html中包含jquery文件

    <head>
        <title>Angular 2 QuickStart</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">
    
        <!-- jquery file -->
        <script src="js/jquery-2.0.3.min.js"></script>
        <script src="js/jquery-ui.js"></script>
        <script src="node_modules/es6-shim/es6-shim.min.js"></script>
        <script src="node_modules/zone.js/dist/zone.js"></script>
        <script src="node_modules/reflect-metadata/Reflect.js"></script>
        <script src="node_modules/systemjs/dist/system.src.js"></script>
        <script src="systemjs.config.js"></script>
        <script>
          System.import('app').catch(function(err){ console.error(err); });
        </script>
      </head>
    

    您可以按照以下方式使用Jquery,我在这里使用JQuery Ui日期选择器 .

    import { Directive, ElementRef} from '@angular/core';
        declare  var $:any;
        @Directive({
          selector: '[uiDatePicker]',
         })
        export class UiDatePickerDirective {
          private el: HTMLElement;
          constructor(el: ElementRef) {
            this.el = el.nativeElement;
    
         }
    
        ngOnInit() {
            $(this.el).datepicker({
             onSelect: function(dateText:string) {
                //do something on select
             }
            });
        }
    }
    

    这对我有用 .

  • 24

    您也可以尝试使用"InjectionToken"导入它 . 如下所述:Use jQuery in Angular/Typescript without a type definition

    您可以简单地注入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();
        }
    }
    
  • 9

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

    import * as $ from 'jquery';
    

    将起作用,但通过创建服务还有另一种“有角度”的方法 .

    第一步1:创建 jquery.service.ts file .

    // 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作为服务与导入*作为$来自'jquery';

  • 2

    安装jquery

    终端$ npm install jquery

    (对于bootstrap 4 ......)

    终端$ npm install popper.js

    终端$ npm install bootstrap

    然后将 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";
    
  • 12

    在Angular2中使用Jquery(4)

    请遵循以下设定

    安装Jquery和Juqry类型定义

    对于Jquery安装 npm install jquery --save

    对于Jquery Type定义安装 npm install @types/jquery --save-dev

    然后只需导入jquery

    import { Component } from '@angular/core';
    import * as $ from 'jquery';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent { 
      console.log($(window)); // jquery is accessible 
    }
    

相关问题