410

Can anyone tell me, how to use jQuery with Angular?

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

I'm aware there are workarounds like manipulating the class or id of the DOM element upfront, but I'm hoping for a cleaner way of doing it.

ishandutta2007
  • 16,676
  • 16
  • 93
  • 129
Waog
  • 7,127
  • 5
  • 25
  • 37
  • 2
    Don't know which version you were using at the time you posted but to me adding JQuery cdn in index.html is enough to call $ in a component – theFreedomBanana Mar 10 '16 at 15:42
  • 4
    It might help http://www.code-sample.com/2016/07/use-jquery-with-angular-2.html – Anil Singh Jul 13 '16 at 07:30
  • please refer below link to use Jquery in Angular 2- http://stackoverflow.com/a/42044459/1089766 – user1089766 Feb 04 '17 at 19:12
  • Just follow these simple steps here: http://stackoverflow.com/a/42295505/7532440 – AmanDeepSharma Mar 10 '17 at 10:05
  • 13
    While some jQuery functionality (especially plugins or jQueryUI) can be very useful in an Angular2 app, it is not best practice to query and manipulate the DOM from inside Angular2 components, as you described in your question. In Angular2 apps the DOM elements you want to manipulate should be bound to your component model. DOM elements state should change according to model changes. Check out this answer: http://stackoverflow.com/questions/42411744/best-practice-of-angular-2 – Benyamin Shoham Mar 30 '17 at 11:05
  • 4
    If you are looking to query DOM elements, you should try Angular Renderer2 instead of jQuery. https://angular.io/api/core/Renderer2 – Kay Oct 02 '17 at 15:12
  • 9
    I think the correct answer for this is: You Dont. Angular is more advanced and newer than jquery, its not outdated and has a lot cleaner code – mast3rd3mon May 22 '18 at 13:26
  • 10
    Why should a person use JQuery with Angular? – Christian Vincenzo Traina May 25 '18 at 09:08
  • 2
    @Cristian Tralna What if someone wants to use existing jQuery based libraries in angular application? Though I understand that Angular and Jquery are 2 different world from architectural point of view but lets say someone have lots of functionality (or few lines of code which is very importent) coded in jquery based libraries, He/She might needed to use jquery $ along with typescript. – Talk is Cheap Show me Code Oct 01 '18 at 12:10
  • You can read my blog post here https://ngohungphuc.wordpress.com/2019/02/07/using-jquery-with-angular/ –  Mar 28 '19 at 14:24
  • you can use ElementRef instead, just look angular documentation – freedom May 22 '19 at 05:30
  • When you use Angular, try not to use the jquery library. Try using the features and the libraries that are produced for angular framework. If you want to use the jquery functions like **find()**, **html()**, **closest()** and etc.., I suggest using the pure js. example: **querySelector()**, **innerHTML**, **parentElement** and etc... – mojtaba ramezani Apr 19 '19 at 05:24
  • @mast3rd3mon I've heard this said over and over, and starting to think it's just groupthink. I see things tout "jquery free" and think it's just a personal goal or something, the user doesn't know or care, and whether they say it or not, Google isn't really going to get rid of nativeelement. Bootstrap modal is really the only place I tend to use it, but it just seems like there's a cult against it "just because". Plus, it's really not that hard to refactor out if it ever needs to go, provided there's not a better way to do things. – Dan Chase Dec 17 '21 at 03:04

26 Answers26

363

Using jQuery from Angular2 is a breeze compared to ng1. If you are using TypeScript you could first reference jQuery typescript definition.

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

TypescriptDefinitions are not required since you could just use any as the type for $ or jQuery

In your angular component you should reference a DOM element from the template using @ViewChild() After the view has been initialized you can use the nativeElement property of this object and pass to jQuery.

Declaring $ (or jQuery) as JQueryStatic will give you a typed reference to 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);

This example is available on plunker: http://plnkr.co/edit/Nq9LnK?p=preview

tslint will complain about chosen not being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file

interface JQuery {
    chosen(options?:any):JQuery;
}    
werenskjold
  • 3,814
  • 1
  • 12
  • 13
  • It works! thx. Unfortunately the doc of `ElementRef.domElement` states *(DEPRECATED way of accessing the DOM, replacement coming)*. Also the `setTimeout` seems like a workaround. Thank you anyway :) – Waog Jun 14 '15 at 13:25
  • 2
    I'm not sure why the `setTimeout` workaround is required. I have tried with several other jQuery components, and it seems like all of them require this workaround for correct initialization. I hope this will change in future release of ng2 – werenskjold Jun 15 '15 at 04:36
  • 1
    Because while construction there is only some *Phantom DOM Element* instead of the final element. The actual Element is only available after the constructor is finished. – Waog Jun 15 '15 at 07:14
  • 1
    I have some issues while using jquery plugins with angular 2 router (dropzone , chosen ... ) . When a component is loaded in the outlet the constructor is called and the template is processed ... the jquery plugin ( with the setTimout hack ) can be initialised .. but when you load another component ( with the router ) and you come back to the first component .. Angular2 recycle the view ( despite that it recalls the constructor ) .. so the elements constructed by Angular plugins in the first time are shown again :( – Mourad Zouabi Aug 24 '15 at 13:05
  • 7
    new callbacks have been added in alpha37 https://github.com/angular/angular/blob/2.0.0-alpha.37/CHANGELOG.md core: added afterContentInit, afterViewInit, and afterViewChecked hooks (d49bc43), closes #3897 – Mourad Zouabi Sep 10 '15 at 11:58
  • @MouradZouabi: For those of us that are new to this, could you explain the significance of your comment? An additional answer would really be awesome! (thx if so!!) – Brian Topping Oct 04 '15 at 01:32
  • You can implement the lifecycle hook **afterViewInit()** to add some DOM manipulations afterViewInit() { var el:any = elelemtRef.domElement.children[0]; $(el).chosen().on('change', (e, args) => { _this.selectedValue = args.selected; }); } Be careful when using router because angular2 may recycle view .. so you have to be sure that the DOM elements manipulations are done only in the first call of afterViewInit .. ( You can use static boolean variables to do so ) – Mourad Zouabi Oct 04 '15 at 18:44
  • Have you tryed using this with data that comes from a http request? Thanks for your response. – ErvTheDev Mar 17 '16 at 11:15
  • 1
    Thanks for your answer, it helped me a lot! Thought I'm using `typings` now, what about updating your comment with `typings` instead of `tsd`? I was thinking it could help others :) – Yannick Morel May 27 '16 at 15:37
  • 22
    this isn't that difficult to set up, but it's certainly not "a breeze" compared to angular 1. in angular 1 you didn't have to do anything, and you could just use jquery anywhere. angular 1 is built on top of jquery. – user428517 Sep 14 '16 at 22:36
  • 8
    After installing definitions though typings, JQueryStatic is still not recognized. – Gonzalo Nov 04 '16 at 19:30
  • I have same issue as Gonzalo – Guerrilla Mar 21 '17 at 04:38
  • 4
    I think we need to update this a bit as now we use NPM for typings – Jackie Mar 21 '17 at 13:19
  • 2
    `npm install @types/jquery --save` – Martin Schneider Apr 20 '17 at 08:40
  • Note that if your element in the template is within an *ngIf, the ElementRef returns undefined. Use [hidden] instead – S Raghav Apr 26 '17 at 04:37
  • 1
    In the npm docs, it says you should be able to do `import $ from "jquery"` should that work? (It doesn't appear to) - https://www.npmjs.com/package/jquery – chrismarx Apr 27 '17 at 16:10
  • Better use Renderer2 class to manipulate the dom. https://angular.io/api/core/Renderer2 – maximz101 Dec 21 '17 at 11:37
  • after installing jquery via nmp, import it like this `declare var $:any;` or `import $ from "jquery"; ` – Sergio A. Feb 07 '19 at 15:44
160

This is what worked for me.

STEP 1 - First things first

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

STEP 2 - IMPORT

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

Lately, I'm writing code with ES6 instead of typescript and am able to import without * as $ in the import statement. This is what it looks like now:

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

Good Luck.

Aakash
  • 21,375
  • 7
  • 100
  • 81
128

Why is everyone making it a rocket science? For anyone else who needs to do some basic stuff on static elements, for example, body tag, just do this:

  1. In index.html add script tag with the path to your jquery lib, doesn't matter where (this way you can also use IE conditional tags to load lower version of jquery for IE9 and less).
  2. In your export component block have a function that calls your code: $("body").addClass("done"); Normaly this causes declaration error, so just after all imports in this .ts file, add declare var $:any; and you are good to go!
Starwave
  • 2,352
  • 2
  • 23
  • 30
  • 1
    Hahaha just jump to your ans and it work thanks :) ;) – GrvTyagi Jul 09 '16 at 06:35
  • 25
    Doesn't work for me. So I am gonna be studying some rocket science. :) – Prajeet Shrestha Aug 23 '16 at 10:01
  • Dude, hands down best answer! Not complicated and worked first try. – Logan H Sep 23 '16 at 17:56
  • 13
    The point of angular 2 is to remove the complexity of dealing with the DOM. Angular 2 has a diff algorithm that will efficiently render your components for you, that's why its better to trick jquery that its manipulating the DOM by pointing it to the angular 2 component, instead of directly manipulating the DOM. – ken Oct 15 '16 at 21:58
  • 5
    intellisense, my friend, that is why – Ayyash Nov 08 '16 at 10:07
  • No doubt it sounded like rocket science before i read your post. Thanks :) – Mani Nov 08 '16 at 20:41
  • 5
    `declare var $:any;` for the win! – tylerlindell Apr 03 '17 at 23:44
  • 2
    This definitely works, but if you're not living in the stone age anymore, go with the accepted answer instead. – jlh Aug 10 '17 at 14:17
  • Great answer !! Don't forget that this is web, we will be dealing with DOM forever – Ignacio Vazquez Sep 05 '17 at 13:27
  • 1
    @Starwave In angular 4 I used some click event using jquery. All are working fine. But the click events not triggered inside the .subscribe(jsonData => {}... i.e inside the subscribe method. Any ideas in it?? – Sam Hanson Mar 26 '18 at 12:16
59

Now it has become very easy, You can do it by simply declaring jQuery variable with any type inside Angular2 controller.

declare var jQuery:any;

Add this just after import statements and before component decorator.

To access any element with id X or Class X you just have to do

jQuery("#X or .X").someFunc();
Devesh Jadon
  • 7,004
  • 4
  • 22
  • 27
34

A simple way:

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;";
}
Yosam Lee
  • 349
  • 3
  • 5
  • Worked for me. But instead of implements OnInit (which Angular did not want to accept) I used inside MyComponent ngOnInit() { // my jQuery here } – Ilya Kushlianski Jun 27 '17 at 09:06
28

Please follow these simple steps. It worked for me. Lets start with a new angular 2 app to avoid any confusion. I'm using Angular cli. So, install it if you don't have it already. https://cli.angular.io/

Step 1: Create a demo angular 2 app

ng new jquery-demo

you can use any name. Now check if it is working by running below cmd.(Now, make sure that you are pointing to 'jquery-demo' if not use cd command )

ng serve

you will see "app works!" on browser.

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

Run this command on cli (make sure that you are pointing to 'jquery-demo' if not use cd command ):

npm i -g bower --save

Now after successful installation of bower, Create a 'bower.json' file by using below command:

bower init

It will ask for inputs, just press enter for all if you want default values and at the end type "Yes" when it'll ask "Looks good?"

Now you can see a new file (bower.json) in folder "jquery-demo". You can find more info on https://bower.io/

Step 3: Install jquery

Run this command

bower install jquery --save

It will create a new folder (bower_components) which will contain jquery installation folder. Now you have jquery installed in 'bower_components' folder.

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

Open 'angular-cli.json' file (present in 'jquery-demo' folder) and add jquery location in "scripts". It will look like this:

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

Step 5: Write simple jquery code for testing

Open 'app.component.html' file and add a simple code line, The file will look like this:

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

Now Open 'app.component.ts' file and add jquery variable declaration and code for 'p' tag. You should use lifecycle hook ngAfterViewInit() also. After making changes the file will look like this:

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

Now run your angular 2 app by using 'ng serve' command and test it. It should work.

AmanDeepSharma
  • 2,138
  • 4
  • 20
  • 34
  • 3
    IMHO. This is the best approach I still use bower for client-side dependencies. – Fırat Küçük Mar 18 '17 at 09:21
  • "`$("p").click(function(){ $(this).hide(); });`" best example of when **do not** use jQuery in Angular?! – Martin Schneider Apr 20 '17 at 08:51
  • 4
    Isn't it easier to setup just using npm? `npm install jquery --save`, then `"scripts":["../node_modules/jquery/dist/jquery.js"]`, then `import $ from 'jquery';` in *.ts files. What is the advantage using bower? – cs_pupil Aug 28 '17 at 19:34
  • 1
    @cs_pupil You can use npm too but Bower is designed for managing only front end packages. Have a lookup https://stackoverflow.com/questions/18641899/what-is-the-difference-between-bower-and-npm – AmanDeepSharma Aug 29 '17 at 06:10
  • 1
    @AmanDeepSharma, thanks! Oddly enough though, it looks like bower has been deprecated. `npm install bower` yielded: `npm WARN deprecated bower@1.8.0:` (https://stackoverflow.com/a/31219726/3806701) – cs_pupil Aug 29 '17 at 17:45
25

Using Angular Cli

 npm install jquery --save

In angular.json under scripts array

"scripts": [ "node_modules/jquery/dist/jquery.min.js" ] // copy relative path of node_modules>jquery>dist>jquery.min.js to avoid path error

Now to use jQuery, all you have to do is to import it as follows in whatever component you want to use jQuery.

For example importing and using jQuery in root component

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');
}
varundhariyal
  • 1,665
  • 14
  • 19
  • 1
    path is wrong use./node_modules instead of ../node_modules – Vikas Kandari Aug 17 '19 at 21:04
  • 2
    you can also install `@types/jquery` using the command: `npm i --save-dev @types/jquery` and add `"types": ["jquery"]` to the file `tsconfig.app.json` or `tsconfig.lib.json` under `compilerOptions` and this way ommit the `declare var $: any;` statement altogether – Shaybc Dec 20 '21 at 15:53
13

You can implement the lifecycle hook ngAfterViewInit() to add some DOM manipulations

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

Be careful when using router because angular2 may recycle views .. so you have to be sure that the DOM elements manipulations are done only in the first call of afterViewInit .. ( You can use static boolean variables to do so )

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;
        }
    }
}
Mourad Zouabi
  • 2,187
  • 2
  • 15
  • 20
13

If you use angular-cli you can do :

  1. Install the dependency :

    npm install jquery --save

    npm install @types/jquery --save-dev

  2. Import the file :

    Add "../node_modules/jquery/dist/jquery.min.js" to the "script" section in .angular-cli.json file

  3. Declare jquery :

    Add "$" to the "types" section of tsconfig.app.json

You can find more details on official angular cli doc

Jahal
  • 131
  • 1
  • 3
13

step 1: use the command : npm install jquery --save

step 2: you can simply import angular as :

import $ from 'jquery';

that's all .

An example would be :

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


}
Laxmikanta Nayak
  • 375
  • 2
  • 10
12

I do it in simpler way - first install jquery by npm in console: npm install jquery -S and then in component file I just write: let $ = require('.../jquery.min.js') and it works! Here full example from some my code:

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

In teplate I have for instance:

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

EDIT

Alternatively instead of using:

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

use

declare var $: any;

and in your index.html put:

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

This will initialize jquery only once globaly - this is important for instance for use modal windows in bootstrap...

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
10

//installing jquerynpm install jquery --save

//installing type defintion for the jquerytypings install dt~jquery --global --save

//adding jquery library into build configuration file as specified(in "angular-cli-build.js" file)

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

//run the build to add the jquery library in the build ng build

//adding the relative path configuration(in 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'}};

//import the jquery library in your component file

import 'jquery';

below is the code snipppet of my sample component

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(){}
}
BALA
  • 188
  • 1
  • 12
9

To Use Jquery in Angular2(4)

Follow these setps

install the Jquery and Juqry type defination

For Jquery Installation npm install jquery --save

For Jquery Type defination Installation npm install @types/jquery --save-dev

and then simply import the 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 
}
Vasim Hayat
  • 909
  • 11
  • 16
6

First, install jQuery using npm as follows:

npm install jquery — save

Second, go to the ./angular-cli.json file at the root of your Angular CLI project folder, and find the scripts: [] property, and include the path to jQuery as follows:

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

Now, to use jQuery, all you have to do is to import it in whatever component you want to use jQuery.

import * as $ from 'jquery';
(or)
declare var $: any;

Take a look at the below code that uses jQuery to animate div on click, especially in the second line. We are importing everything as $ from 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");
        });
    });
  }
}
Yogesh Waghmare
  • 941
  • 10
  • 10
4

Since I'm a dunce, I thought it would be good to have some working code.

Also, Angular2 typings version of angular-protractor has issues with the jQuery $, so the top accepted answer doesn't give me a clean compile.

Here are the steps that I got to be working:

index.html

<head>
...
    <script   src="https://code.jquery.com/jquery-3.1.1.min.js"   integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
...
</head>

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

    }
}
Jon
  • 7,848
  • 1
  • 40
  • 41
4

Just write

declare var $:any;

after all import sections, you can use jQuery and include the jQuery library in your index.html page

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

it worked for me

wp78de
  • 18,207
  • 7
  • 43
  • 71
4

I am skipping installation of jquery since this point has been mentioned in all of the posts created prior to mine. So, you have already installed jquery. Importing t into your component like this

import * as $ from 'jquery';

will work, but there is another 'angular" way to do this by creating a service.

Step no. 1: create 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');

Step. no. 2: register the service in app.module.ts

import { JQUERY_TOKEN } from './services/jQuery.service';
declare const jQuery: Object;

providers: [
    { provide: JQUERY_TOKEN, useValue: jQuery },
]

Step no. 3: inject the service into your component 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');
    }
}

I will be very grateful if somebody can explain pros and cons of both methods: DI jquery as a service vs. import * as $ from 'jquery';

azakgaim
  • 309
  • 3
  • 6
4

Angular 12

npm i jquery

this is important : npm i @types/jquery

angular.json

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

.ts file

import * as $ from "jquery";
ekremkocak
  • 102
  • 6
3

Others already posted. but I give a simple example here so that can help some new comers.

Step-1: In your index.html file reference jquery cdn

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

Step-2: assume we want to show div or hide div on click of a button:

 <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:In the component file bellow the import declare $ as bellow:

declare var $: any;

than create function like bellow:

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

It will work with latest Angular and JQuery

MJ X
  • 8,506
  • 12
  • 74
  • 99
2


1) To access DOM in component.

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

You can include jQuery in following way. 2) Include you jquery file in index.html before angular2 loads

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

You can use Jquery in following way, Here i am using JQuery Ui date picker.

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

This work for me.

ayyappa maddi
  • 854
  • 3
  • 10
  • 18
2

Global Library Installation as Official documentation here

  1. Install from npm:

    npm install jquery --save

  2. Add needed script files to scripts:

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

Restart server if you're running it, and it should be working on your app.


If you want to use inside single component use import $ from 'jquery'; inside your component

Amr Ibrahim
  • 2,066
  • 2
  • 23
  • 47
1

The most effective way that I have found is to use setTimeout with time of 0 inside of the page/component constructor. This let's the jQuery run in the next execution cycle after Angular has finished loading all the child components. A few other component methods could be used but all I have tried work best when run inside a setTimeout.

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

Here is what worked for me - Angular 2 with webpack

I tried declaring $ as type any but whenever I tried to use any JQuery module I was getting (for example) $(..).datepicker() is not a function

Since I have Jquery included in my vendor.ts file I simply imported it into my component using

import * as $ from 'jquery';

I am able to use Jquery plugins (like bootstrap-datetimepicker) now

S Raghav
  • 1,386
  • 1
  • 16
  • 26
1

You could also try to import it with the "InjectionToken". As described here: Use jQuery in Angular/Typescript without a type definition

You can simply inject the jQuery global instance and use it. For this you won't be needing any type definitions or typings.

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

When set correctly in your 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 { }

You can start using it in your components:

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();
    }
}
Jeffrey Rosselle
  • 745
  • 1
  • 9
  • 25
1

add this code Below in src/Main.ts will important jquery and all function in all project

import * as jquery from 'jquery';
import * as bootstrap from 'bootstrap';

not forget npm i @types/jquery and npm i @types/bootstrap

Mena afefe
  • 11
  • 2
-1

Install jquery

Terminal$ npm install jquery

(For bootstrap 4...)

Terminal$ npm install popper.js

Terminal$ npm install bootstrap

Then add the import statement to app.module.ts.

import 'jquery'

(For bootstrap 4...)

import 'popper.js'
import 'bootstrap'

Now you will no longer need <SCRIPT> tags to reference the JavaScript.

(Any CSS you want to use still has to be referenced in styles.css)

@import "~bootstrap/dist/css/bootstrap.min.css";
Carter Medlin
  • 11,857
  • 5
  • 62
  • 68