[jquery] How to use jQuery Plugin with Angular 4?

I want to use a range slider in an angular project and I tried using one available module for 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.

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

Please let me know.

Thanks in advance!

This question is related to jquery angular

The answer is


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

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'
    }),

  ]
};

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

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...

  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

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 jquery instead of getting it from google's 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-pt2 If 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


Install jQuery using NPM Jquery NPM

npm install jquery

Install the jQuery declaration file

npm install -D @types/jquery

Import jQuery inside .ts

import * as $ from 'jquery';

call inside class

export class JqueryComponent implements OnInit {

constructor() {
}

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

}

Try this:

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

Or add scripts to angular-cli.json:

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

and in your .ts file:

declare var $: any;

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

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

the solution to the typescript:

Step1:

npm install jquery

npm install --save-dev @types/jquery

step2: in Angular.json add:

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

or in index.html add:

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

step3: in *.component.ts where you want to use jquery

import * as $ from 'jquery';  // dont need "declare let $"

Then you can use jquery the same as javaScript. This way, VScode supports auto-suggestion by Typescript


Try using - declare let $ :any;

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


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

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

You should have access to jQuery everywhere.

The following should work:

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

ngOnInit() {
     const $ = window["$"];
     $('.flexslider').flexslider({
        animation: 'slide',
        start: function (slider) {
          $('body').removeClass('loading')
        }
     })
}

You can update your jquery typings version like so

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


Install jquery with npm

npm install jquery --save

Add typings

npm install --save-dev @types/jquery

Add scripts to angular-cli.json

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

Build project and serve

ng build

Hope this helps! Enjoy coding