【问题标题】:How to use jQuery with Angular?如何在 Angular 中使用 jQuery?
【发布时间】:2015-08-17 21:11:55
【问题描述】:

谁能告诉我,如何将 jQueryAngular 一起使用?

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

我知道有一些解决方法,例如预先操作 DOM 元素的 classid,但我希望有一种更简洁的方法。

【问题讨论】:

  • 虽然某些 jQuery 功能(尤其是插件或 jQueryUI)在 Angular2 应用程序中可能非常有用,但正如您在问题中所述,从 Angular2 组件内部查询和操作 DOM 并不是最佳实践。在 Angular2 应用程序中,您想要操作的 DOM 元素应该绑定到您的组件模型。 DOM 元素的状态应该根据模型的变化而变化。看看这个答案:stackoverflow.com/questions/42411744/best-practice-of-angular-2
  • 如果你想查询 DOM 元素,你应该尝试 Angular Renderer2 而不是 jQuery。 angular.io/api/core/Renderer2
  • 我认为正确的答案是:你不会。 Angular 比 jquery 更先进和更新,它没有过时并且代码更简洁
  • 为什么要在 Angular 中使用 JQuery?

标签: jquery angular


【解决方案1】:

与 ng1 相比,在 Angular2 中使用 jQuery 是轻而易举的事。如果你使用 TypeScript,你可以先参考 jQuery typescript 定义。

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

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

在您的 Angular 组件中,您应该使用 @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;
}    

【讨论】:

  • 我不确定为什么需要 setTimeout 解决方法。我已经尝试过使用其他几个 jQuery 组件,似乎所有这些组件都需要这种解决方法才能正确初始化。我希望这会在 ng2 的未来版本中有所改变
  • 在 alpha37 中添加了新的回调 github.com/angular/angular/blob/2.0.0-alpha.37/CHANGELOG.md 核心:添加了 afterContentInit、afterViewInit 和 afterViewChecked 钩子 (d49bc43),关闭 #3897
  • 这并不难设置,但与角度 1 相比,它肯定不是“轻而易举”。在角度 1 中,您无需执行任何操作,您可以在任何地方使用 jquery . angular 1 建立在 jquery 之上。
  • 通过打字安装定义后,仍然无法识别JQueryStatic。
  • 我认为我们需要稍微更新一下,因为现在我们使用 NPM 进行打字
【解决方案2】:

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

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

使用路由器时要小心,因为 angular2 可能会回收视图 .. 所以您必须确保仅在第一次调用 afterViewInit 时完成 DOM 元素操作 ..(您可以使用静态布尔变量来执行此操作)

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

【讨论】:

  • Property 'domElement' does not exist on type ElementRef
【解决方案3】:

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

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

【讨论】:

  • 你绝对应该使用ngOnInit() 而不是这个
  • ngAfterViewInit()
  • setTimeout 如果您在 *ngFor 中有许多项目要渲染完成,则实际上并不能正常工作。
【解决方案4】:


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 之前将 jquery 文件包含在 index.html 中

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

这对我有用。

【讨论】:

    【解决方案5】:

    我以更简单的方式来做——首先在控制台中通过 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>
    

    编辑

    替代使用:

    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 - 这对于例如在引导程序中使用模式窗口很重要...

    【讨论】:

    • 我不知道我从不使用 angular-cli,但我使用 angular2-webpack-starter 并且它在那里工作。
    • 那个 require 方法是从哪里来的?
    • 你打错了 => console.log({ conatiner : this.container}); 把它改成console.log({ container: this.container});
    【解决方案6】:

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

    1. 在 index.html 中添加 script 标签和 jquery lib 的路径,在哪里都没有关系(这样你也可以使用 IE 条件标签为 IE9 和更低版本加载较低版本的 jquery)。
    2. 在您的 export component 块中有一个调用您的代码的函数:$("body").addClass("done"); 通常这会导致声明错误,所以在此 .ts 文件中的所有导入之后,添加 declare var $:any; 就可以了!李>

    【讨论】:

    • 对我不起作用。所以我要学习一些火箭科学。 :)
    • angular 2的重点是去除处理DOM的复杂性。 Angular 2 有一个 diff 算法,可以有效地为你渲染你的组件,这就是为什么它更好地欺骗 jquery,它通过将它指向 angular 2 组件来操纵 DOM,而不是直接操纵 DOM。
    • 智能感知,我的朋友,这就是为什么
    • declare var $:any; 赢了!
    • 这绝对有效,但如果您不再生活在石器时代,请选择接受的答案。
    【解决方案7】:

    现在它变得非常简单,你可以通过在Angular2控制器中简单地用任何类型声明jQuery变量来做到这一点。

    declare var jQuery:any;
    

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

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

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

    【讨论】:

    • 已验证,这适用于带有 webpack 的 angular 2(由 yeoman Aspnetcore SPA 生成的 SPA 模板)。通常最简单的方法效果最好!谢谢。
    • 我在我的项目中使用它,但是缺少这种方法是我们失去了 jQuery 类型的所有强大类型能力:)
    • 在 Angular 6 (6.0.3) 中工作
    • 工作环境:Angular CLI:7.1.4 节点:10.15.0
    【解决方案8】:

    //安装jquerynpm install jquery --save

    //为jquerytypings 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';
    

    下面是我的示例组件的代码片段

    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(){}
    }
    

    【讨论】:

    • 太棒了,它非常适合 ng-cli 项目。谢谢!
    • 超级流畅!我正在为我的项目使用 Angular-cli,这是黄金!摇滚
    • 我没有 'angular-cli-build.js' 文件:/
    【解决方案9】:

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

    另外,angular-protractor has issues with the jQuery$ 的 Angular2 类型版本,所以最接受的答案并没有给我一个干净的编译。

    以下是我必须工作的步骤:

    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】:

      随便写

      declare var $:any;
      

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

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

      它对我有用

      【讨论】:

        【解决方案11】:

        这对我有用。

        第 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 - Feb - 2017

        最近,我正在使用ES6 而不是typescript 编写代码,并且能够在import statement 中不使用* as $ 来编写import。这是现在的样子:

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

        祝你好运。

        【讨论】:

        • 花了我一个小时来弄清楚如何将 jQuery 放入 Angular 2(正确)... 很确定 Web 开发正在倒退。
        • 为了从'jquery'工作导入$,你需要设置--allowJs
        • import * as $ from 'jquery'; in app.module.ts 使其可用于整个项目。顺便说一句:"Why --save instead of --save-dev?"
        • import $ from 'jquery'; 这是 imo 页面上最漂亮的 jquery 导入语句。正是我想要的样子。
        • @Starboy 那是因为你不应该在 Angular 应用程序中需要任何 JQuery,如果你这样做了,你很可能做错了什么。
        【解决方案12】:

        请按照这些简单的步骤。它对我有用。让我们从一个新的 angular 2 应用程序开始,以避免任何混淆。我正在使用 Angular cli。因此,如果您还没有它,请安装它。 https://cli.angular.io/

        第 1 步:创建演示 angular 2 应用

        ng new jquery-demo
        

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

        ng serve
        

        您将看到“应用程序有效!”在浏览器上。

        第 2 步:安装 Bower(网络包管理器)

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

        npm i -g bower --save
        

        在成功安装 bower 后,使用以下命令创建一个 'bower.json' 文件:

        bower init
        

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

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

        第 3 步:安装 jquery

        运行此命令

        bower install jquery --save
        

        它将创建一个包含 jquery 安装文件夹的新文件夹 (bower_components)。现在您已将 jquery 安装在“bower_components”文件夹中。

        第 4 步:在 'angular-cli.json' 文件中添加 jquery 位置

        打开“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' 文件并为 '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 应用程序并对其进行测试。它应该可以工作。

        【讨论】:

        • 恕我直言。这是我仍然使用 bower 来处理客户端依赖项的最佳方法。
        • "$("p").click(function(){ $(this).hide(); });"不要在 Angular 中使用 jQuery 的最佳示例?!
        • 使用 npm 设置不是更容易吗? npm install jquery --save,然后是 "scripts":["../node_modules/jquery/dist/jquery.js"],然后是 *.ts 文件中的 import $ from 'jquery';。使用凉亭有什么好处?
        • @cs_pupil 您也可以使用 npm,但 Bower 旨在仅管理前端包。查找stackoverflow.com/questions/18641899/…
        • @AmanDeepSharma,谢谢!奇怪的是,看起来凉亭已被弃用。 npm install bower 产生:npm WARN deprecated bower@1.8.0: (stackoverflow.com/a/31219726/3806701)
        【解决方案13】:

        这对我有用 - Angular 2 和 webpack

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

        因为我的 vendor.ts 文件中包含了 Jquery,所以我只是使用

        将它导入到我的组件中

        import * as $ from 'jquery';

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

        【讨论】:

        • 请注意,您的应用需要 5 倍的时间来引导。
        • @jake 是因为加载引导库需要时间吗?
        • 不,jquery 需要更长的时间。引导程序!== 推特引导程序
        • @jake 哎呀!我猜我的意思是jquery。感谢您的来信
        • @jake 你介意解释一下为什么通过让整个应用程序都可以使用 jquery 来解释为什么一个应用程序需要 5 倍的时间来引导
        【解决方案14】:

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

        【讨论】:

          【解决方案15】:

          在 Angular2(4) 中使用 Jquery

          遵循这些设置

          安装 Jquery 和 Juqry 类型定义

          Jquery安装npm install jquery --save

          对于Jquery类型定义安装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 
          }
          

          【讨论】:

          【解决方案16】:

          一个简单的方法:

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

          【讨论】:

          • 为我工作。但是我没有实现 OnInit(Angular 不想接受),而是在 MyComponent ngOnInit() { // my jQuery here } 中使用
          【解决方案17】:

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

          1. 安装依赖

            npm install jquery --save

            npm install @types/jquery --save-dev

          2. 导入文件

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

          3. 声明 jquery

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

          您可以在official angular cli doc找到更多详细信息

          【讨论】:

          • 这会在构建时导致以下错误:错误 TS2688 中的错误:找不到“$”的类型定义文件。
          • 错误 TS1192:模块 ''jquery'' 没有默认导出
          【解决方案18】:

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

          【讨论】:

          • Module ..node_modules/@types/jquery/index"' 没有默认导出
          【解决方案19】:

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

          import * as $ from 'jquery';
          

          会起作用,但还有另一种“角度”的方法可以通过创建服务来做到这一点。

          步骤号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';

          【讨论】:

            【解决方案20】:

            安装jquery

            终端$npm install jquery

            (对于引导程序 4...)

            终端$npm install popper.js

            终端$npm install bootstrap

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

            import 'jquery'
            

            (对于引导程序 4...)

            import 'popper.js'
            import 'bootstrap'
            

            现在您将不再需要 &lt;SCRIPT&gt; 标记来引用 JavaScript。

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

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

            【讨论】:

              【解决方案21】:

              全局库安装 as Official documentation here

              1. 从 npm 安装:

                npm install jquery --save

              2. 将所需的脚本文件添加到脚本中:

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

              如果您正在运行它,请重新启动服务器,它应该可以在您的应用上运行。


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

              【讨论】:

                【解决方案22】:

                使用 Angular Cli

                 npm install jquery --save
                

                在scripts数组下的angular.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');
                }
                

                【讨论】:

                • 路径错误使用./node_modules 而不是../node_modules
                • 您也可以使用以下命令安装@types/jquerynpm i --save-dev @types/jquery 并将"types": ["jquery"] 添加到文件tsconfig.app.jsontsconfig.lib.jsoncompilerOptions 下,这样就省略了declare var $: any; 语句完全
                【解决方案23】:

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

                第 1 步:在您的 index.html 文件中引用 jquery cdn

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

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

                Step-3:在组件文件下面的 import 中声明 $ 如下:

                declare var $: any;
                

                比创建如下函数:

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

                它将适用于最新的 Angular 和 JQuery

                【讨论】:

                  【解决方案24】:

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

                  npm install jquery — save
                  

                  其次,转到 Angular CLI 项目文件夹根目录下的 ./angular-cli.json 文件,找到 scripts: [] 属性,并包含 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");
                          });
                      });
                    }
                  }
                  

                  【讨论】:

                    【解决方案25】:

                    Angular 12

                    npm i jquery

                    这很重要:npm i @types/jquery

                    angular.json

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

                    .ts 文件

                    import * as $ from "jquery";
                    

                    【讨论】:

                      猜你喜欢
                      • 2016-05-25
                      • 2017-06-11
                      • 2017-12-02
                      • 2019-04-13
                      • 1970-01-01
                      • 2019-12-16
                      • 2017-10-11
                      • 1970-01-01
                      相关资源
                      最近更新 更多