How to use jQuery Plugin with Angular 4?

JqueryAngular

Jquery Problem Overview


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!

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

Yes you can use jquery with Angular 4

Steps:

  1. In index.html put below line in tag.

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

  1. In component ts file below you have to declare var like this

    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:

This will work for you. Thanks

Solution 3 - Jquery

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

}

Solution 4 - Jquery

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

Solution 5 - 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

Solution 6 - Jquery

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;

Solution 7 - Jquery

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

Solution 8 - Jquery

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

Solution 9 - Jquery

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

  ]
};

Solution 10 - Jquery

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

Solution 11 - Jquery

Try using - declare let $ :any;

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

Solution 12 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSP-TYView Question on Stackoverflow
Solution 1 - JqueryErvTheDevView Answer on Stackoverflow
Solution 2 - JqueryGAURAV ROYView Answer on Stackoverflow
Solution 3 - JqueryGovarthanan VenunathanView Answer on Stackoverflow
Solution 4 - JquerySooriView Answer on Stackoverflow
Solution 5 - JqueryPhilView Answer on Stackoverflow
Solution 6 - JqueryBettaibi NidhalView Answer on Stackoverflow
Solution 7 - JqueryDidi PeppleView Answer on Stackoverflow
Solution 8 - JqueryGuaracy A. LimaView Answer on Stackoverflow
Solution 9 - JqueryDavid DehghanView Answer on Stackoverflow
Solution 10 - JqueryHungNM2View Answer on Stackoverflow
Solution 11 - JqueryAnshu BansalView Answer on Stackoverflow
Solution 12 - JqueryІгор МацюкView Answer on Stackoverflow