如何在 Angular 4 中使用 jQuery 插件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43934727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:20:28  来源:igfitidea点击:

How to use jQuery Plugin with Angular 4?

jqueryangular

提问by SP-TY

I want to use a range slider in an angular project and I tried using one available module for angular 4.

我想在一个 angular 项目中使用一个范围滑块,我尝试使用一个可用的 angular 4 模块。

It works fine during compilation but when I try to build it for deployment, it throws the below error.

它在编译期间工作正常,但是当我尝试构建它以进行部署时,它会引发以下错误。

enter image description here

在此处输入图片说明

I checked for the option of using jQuery plugin directly in the angular project and I'm only getting options for doing it in Angular 2.

我检查了在 angular 项目中直接使用 jQuery 插件的选项,我只得到了在 Angular 2 中执行它的选项。

Is there any way we can use jQuery plugins in Angular 4?

有什么办法可以在 Angular 4 中使用 jQuery 插件吗?

Please let me know.

请告诉我。

Thanks in advance!

提前致谢!

回答by Ervin Llojku

Install jquery with npm

使用 npm 安装 jquery

npm install jquery --save

Add typings

添加类型

npm install --save-dev @types/jquery

Add scripts to angular-cli.json

将脚本添加到 angular-cli.json

"apps": [{
  ...
  "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
  ],
  ...
}]

Build project and serve

构建项目并服务

ng build

Hope this helps! Enjoy coding

希望这可以帮助!享受编码

回答by GAURAV ROY

Yes you can use jquery with Angular 4

是的,您可以在 Angular 4 中使用 jquery

Steps:

脚步:

1) In index.htmlput below line in tag.

1)在index.html标签中放在下面的行中。

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

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

2) In component ts file below you have to declare var like this

2)在下面的组件 ts 文件中,您必须像这样声明 var

import { Component } from '@angular/core';
declare var jquery:any;
declare var $ :any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular 4 with jquery';
  toggleTitle(){
    $('.title').slideToggle(); //
  }

}

And use this code for corresponding html file like this:

并将此代码用于相应的 html 文件,如下所示:

<h1 class="title" style="display:none">
  {{title}}
</h1>
<button (click)="toggleTitle()"> clickhere</button>

This will work for you. Thanks

这对你有用。谢谢

回答by Govarthanan Venunathan

Install jQuery using NPM Jquery NPM

使用 NPM 安装 jQuery Jquery NPM

npm install jquery

Install the jQuery declaration file

安装 jQuery 声明文件

npm install -D @types/jquery

Import jQuery inside .ts

在 .ts 中导入 jQuery

import * as $ from 'jquery';

call inside class

在课堂内调用

export class JqueryComponent implements OnInit {

constructor() {
}

ngOnInit() {
    $(window).click(function () {
        alert('ok');
        });
    }

}

回答by Soori

You are not required to declare any jQuery variable as you installed @types/jquery.

在安装@types/jquery 时,您不需要声明任何 jQuery 变量。

declare var jquery:any;   // not required
declare var $ :any;   // not required

You should have access to jQuery everywhere.

您应该可以在任何地方访问 jQuery。

The following should work:

以下应该工作:

jQuery('.title').slideToggle();

回答by Phil

You should not use jQuery in Angular. While it is possible (see other answers for this question), it is discouraged. Why?

你不应该在 Angular 中使用 jQuery。虽然这是可能的(请参阅此问题的其他答案),但不鼓励这样做。为什么?

Angular holds an own representation of the DOM in its memory and doesn't use query-selectors (functions like document.getElementById(id)) like jQuery. Instead all the DOM-manipulation is done by Renderer2 (and Angular-directives like *ngFor and *ngIf accessing that Renderer2 in the background/framework-code). If you manipulate DOM with jQuery yourself you will sooner or later...

Angular 在其内存中拥有自己的 DOM 表示,并且document.getElementById(id)不像 jQuery那样使用查询选择器(类似 函数)。相反,所有 DOM 操作都是由 Renderer2 完成的(以及像 *ngFor 和 *ngIf 这样的 Angular 指令在后台/框架代码中访问该 Renderer2)。如果您自己使用 jQuery 操作 DOM,您迟早会...

  1. Run into synchronization problems and have things wrongly appearing or not disappearing at the right time from your screen
  2. Have performance issues in more complex components, as Angular's internal DOM-representation is bound to zone.js and its change detection-mechanism - so updating the DOM manually will always block the thread your app is running on.
  3. Have other confusing errors you don't know the origin of.
  4. Not being able to test the application correctly (Jasmine requires you to know when elements have been rendered)
  5. Not being able to use Angular Universal or WebWorkers
  1. 遇到同步问题,并在正确的时间从屏幕上错误地出现或消失
  2. 在更复杂的组件中存在性能问题,因为 Angular 的内部 DOM 表示绑定到 zone.js 及其更改检测机制 - 因此手动更新 DOM 将始终阻止您的应用程序正在运行的线程。
  3. 有其他令人困惑的错误,您不知道其来源。
  4. 无法正确测试应用程序(Jasmine 要求您知道元素何时呈现)
  5. 无法使用 Angular Universal 或 WebWorkers

If you really want to include jQuery (for duck-taping some prototype that you will 100% definitively throw away), I recommend to at least include it in your package.json with npm install --save jqueryinstead of getting it from google's CDN.

如果您真的想包含 jQuery(用于对一些您将 100% 明确丢弃的原型进行录音),我建议至少将它包含在您的 package.json 中,npm install --save jquery而不是从 google 的 CDN 中获取。

TLDR: For learning how to manipulate the DOM in the Angular way please go through the official tour-of heroes tutorial first: https://angular.io/tutorial/toh-pt2If you need to access elements higher up in the DOM hierarchy (parent or document body) or for some other reason directives like *ngIf, *ngFor, custom directives, pipes and other angular utilities like [style.background], [class.myOwnCustomClass]don't satisfy your needs, use Renderer2: https://www.concretepage.com/angular-2/angular-4-renderer2-example

TLDR:要学习如何以 Angular 方式操作 DOM,请先阅读官方英雄教程:https: //angular.io/tutorial/toh-pt2如果您需要访问 DOM 层次结构中更高的元素(父母或document body)或其他一些原因的指示一样*ngIf*ngFor定制指令,管道等角度实用工具,比如[style.background][class.myOwnCustomClass]不能满足您的需求,使用Renderer2:https://www.concretepage.com/angular-2/angular-4 -renderer2-example

回答by Bettaibi Nidhal

Try this:

尝试这个:

import * as $ from 'jquery/dist/jquery.min.js';

Or add scripts to angular-cli.json:

或者在 angular-cli.json 中添加脚本:

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

and in your .ts file:

并在您的 .ts 文件中:

declare var $: any;

回答by Didi Pepple

You can update your jquery typings version like so

您可以像这样更新您的 jquery 类型版本

npm install --save @types/jquery@latest

I had this same error and I've been at if for 5 days surfing the net for a solution.it worked for me and it should work for you

我有同样的错误,我已经在网上冲浪了 5 天寻找解决方案。它对我有用,应该对你有用

回答by David Dehghan

You can use webpack to provideit. It will be then injected DOM automatically.

你可以使用 webpack 来提供它。然后它会被自动注入 DOM。

module.exports = {
  context: process.cwd(),
  entry: {
    something: [
      path.join(root, 'src/something.ts')
    ],
    vendor: ['jquery']
  },
  devtool: 'source-map',
  output: {
    path: path.join(root, '/dist/js'),
    sourceMapFilename: "[name].js.map",
    filename: '[name].js'
  },
  module: {
    rules: [
      {test: /\.ts$/, exclude: /node_modules/, loader: 'ts-loader'}
    ]
  },
  resolve: {
    extensions: ['.ts', '.es6', '.js', '.json']
  },
  plugins: [

    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    }),

  ]
};

回答by Guaracy A. Lima

If you have the need to use other libraries in projects --typescript-- not just in projects - angle - you can look for tds's (TypeScript Declaration File) that are depares and that have information of methods, types, functions, etc. , which can be used by TypeScript, usually without the need for import. declare var is the last resource

如果您需要在项目中使用其他库--typescript--而不仅仅是在项目中-角度-您可以查找 tds(TypeScript 声明文件),它们是 depares 并且具有方法、类型、函数等信息,可以被 TypeScript 使用,通常不需要导入。声明 var 是最后一个资源

npm install @types/lib-name --save-dev

回答by Anshu Bansal

Try using - declare let $ :any;

尝试使用 - 声明 let $ :any;

or import * as $ from 'jquery/dist/jquery.min.js'; provide exact path of the lib

或从 'jquery/dist/jquery.min.js' 导入 * 作为 $; 提供lib的确切路径