18

I want to wrap some jQuery code in an Angular2 directive.

I installed jQuery library for Typings into my project with the following command:

typings install dt~jquery --save --global

So now i have jquery folder under typings/global folder in my project directory. In addition the following new line has been added to my typings.json file:

{
    "globalDependencies": {
        "core-js": "registry:dt/core-js#0.0.0+20160602141332",
        "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
        "node": "registry:dt/node#6.0.0+20160807145350",
        "jquery": "registry:dt/jquery#1.10.0+20160908203239"
    }
}

I started to write a new Angular2 directive (that I imported into app-module file) but I do not know how to correctly import jQuery library. Here is my source file:

import {Directive} from '@angular/core';

@Directive({
    selector: "my-first-directive"
})

export class MyFirstDirective {
    constructor() {
        $(document).ready(function () {
            alert("Hello World");
        });
    }
}

But I can't use nor $ nor jQuery. What is the next step?

micnic
  • 10,915
  • 5
  • 44
  • 55
smartmouse
  • 13,912
  • 34
  • 100
  • 166

7 Answers7

27

Step 1: get jquery in your project

npm install jquery

Step 2: add type for jquery

npm install -D @types/jquery

Step 3: Use it in your component!

import * as $ from 'jquery';

Ready to use $!

Chinmay
  • 4,726
  • 6
  • 29
  • 36
4

If you are using "@angular/cli" then install:

npm install jquery --save

Second step install:

install: npm install @types/jquery --save-dev

And find your file name in "angular-cli.json" on the root and add the inside of as like:

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

Now it will work.

Sheo Sagar
  • 897
  • 9
  • 9
3

jQuery.service.ts

 import { OpaqueToken } from '@angular/core'
export let JQ_TOKEN = new OpaqueToken('jQuery');

index.ts`

export * from './jQuery.service';

app.module.ts

declare let jQuery : Object;

@NgModule({
  providers: [
    { provide: TOASTR_TOKEN, useValue: toastr },
    { provide: JQ_TOKEN, useValue: jQuery },
})
export class AppModule { }

how to use Jquery in component

   import { Component, Input, ViewChild, ElementRef, Inject } from '@angular/core'
import { JQ_TOKEN } from './jQuery.service'

@Component({
  selector: 'simple-modal',
  template: `
  <div id="{{elementId}}" #modalcontainer class="modal fade" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
          <h4 class="modal-title">{{title}}</h4>
        </div>
        <div class="modal-body" (click)="closeModal()">
          <ng-content></ng-content>
        </div>
      </div>
    </div>
  </div>
  `,
  styles: [`
    .modal-body { height: 250px; overflow-y: scroll; }
  `]
})
export class SimpleModalComponent {
  @Input() title: string;
  @Input() elementId: string;
  @Input() closeOnBodyClick: string;
  @ViewChild('modalcontainer') containerEl: ElementRef;

  constructor(@Inject(JQ_TOKEN) private $: any) {}

  closeModal() {
    if(this.closeOnBodyClick.toLocaleLowerCase() === "true") {
      this.$(this.containerEl.nativeElement).modal('hide');
    }
  }
}
user1089766
  • 597
  • 6
  • 14
  • OpaqueToken is deprecated though, but you can simply change it with the InjectionToken as described here https://thecodegarden.net/jquery-in-angular-typescript-without-type-definition/ – Jeffrey Rosselle May 16 '17 at 14:58
2

You could also load your jQuery Javascript file in a normal script tag in the head section of your index.html.

<html>
    <head>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" />
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.js" />

        ...
    </head>
    ...

Then in the component or directive where you need it, just declare the $ variable needed for jQuery, since you won't have the typings for all the plugins you need:

import {Directive} from '@angular/core';

declare var $: any;

@Directive({
    selector: "my-first-directive"
})

export class MyFirstDirective {
    constructor() {
        $(document).ready(function () {
            alert("Hello World");
        });
    }
}
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
  • Shoud i write the following line in the `systemjs.config.js}` file? `'jquery': 'typings/global/jquery/index.d.ts'` – smartmouse Sep 15 '16 at 13:32
  • No, no need to write anything in the SystemJS config. Just add a ` – Maximilian Riegler Sep 15 '16 at 13:35
  • Sorry, i'm afraid i don't figure out how it works. Can you show me an example or some code? – smartmouse Sep 15 '16 at 13:38
  • Thank you. It is the first time i see that `reference` tag... why do you need it? Why other replies talk about `systemjs.config.js` file? – smartmouse Sep 15 '16 at 13:45
  • Please, have a look at this: https://plnkr.co/edit/MMNWGh. Here it can uses jQuery and even a jQuery plugin (dropdown) with no reference tag. How does it work in that case? And why that example uses a different way to wrap some jQuery code? – smartmouse Sep 15 '16 at 13:50
  • 2
    this is the oldschool way of doing it. – vidalsasoon Sep 15 '16 at 13:51
  • You can do the same this way - I'll update my answer for your plugin "request". – Maximilian Riegler Sep 15 '16 at 13:54
  • 1
    Not gonna lie - this version of using external JS files will save you a lot of headaches with SystemJS or any packaging tool. – Maximilian Riegler Sep 15 '16 at 14:47
1

You should have a typings.json that points to your jquery typing file. Then:

systemjs.config (notice map setting for jquery)

System.config({
    defaultJSExtensions: true,
    paths: {
        // paths serve as alias
        'npm:': 'node_modules/'
    },
    map: {
        'app':  'app',
        jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js',
        material: 'npm:material-design-lite/dist/material.min.js',

        // angular bundles
        '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
        ....
    },
    packages: {
        app: { main: 'main', format: 'register', defaultExtension: 'js' },
        'rxjs': { defaultExtension: 'js' }
    },
});

In component:

import $ from 'jquery';

Then use $ as usual.

vidalsasoon
  • 4,365
  • 1
  • 32
  • 40
  • So didn't i need to install jQuery with tyipings install? What should i write down as path in the map object of `systemjs.config.js` file? – smartmouse Sep 15 '16 at 13:16
  • you need the typings if you're gonna use "import $ from 'jquery';". If you don't you have to to declare a '$' variable with "any" type or else typescript complains about the wrong type – vidalsasoon Sep 15 '16 at 13:28
  • If i import with `scripts` html tag, i cannot use jQuery for writing code in my Angular2 directives/components. – smartmouse Sep 15 '16 at 13:34
  • don't import with the scripts tag. let typescript and systemjs do it for you and do it the same way angular 2 does it. – vidalsasoon Sep 15 '16 at 13:53
  • Okay, so i add the following line to my `systemjs.config.js` file: `'jquery': 'node_modules/jquery/dist/jquery.min.js'`. As i figured out it works because i install a corresponding "typings" definition file. So, now i add the following line to my directive/component: `import * as $ from 'jquery';`. Is this the right way? – smartmouse Sep 15 '16 at 14:02
  • start with "import $ from 'jquery';" and you should see the intellisense off the "$" working. Test with that first. – vidalsasoon Sep 15 '16 at 14:11
  • If i use `import $ from 'jquery'` instead of `import * as $ from 'jquery'` i get this error in my IDE (Atom): `Module "'jquery'" has no default export.` – smartmouse Sep 15 '16 at 14:13
  • search solution for "declare module "jquery"". Your typings file should have this. – vidalsasoon Sep 15 '16 at 14:18
  • 1
    Why `import * as $ from 'jquery'` does work? Anyway, how to make it work even with `dropdown` jQuery plugin? – smartmouse Sep 15 '16 at 14:19
  • Resolved after installing. npm install @types/jquery --save – roshini Mar 30 '17 at 05:59
0

I don't think it should be a issue to use jquery with angular 2. If the typings and the dependencies for jquery are installed properly, then it should not be a issue to use jquery in angular 2.

I was able to use jquery in my angular 2 project with proper installation. And by proper installation, I mean the installation of jquery typings in order to recognize it in typescript.

After that, I was able to use jquery in following way:

jQuery(document).ready({
    ()=>{
        alert("Hello!");
    };
});
Abhinandan
  • 429
  • 8
  • 13
0

This is old question and there're some answers already. However existing answers are overly complicated ( answer from user1089766 contains many unnecessary stuffs). Hope this helps someone new.

Add <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script> Into your index.html file.

Create jQuery.Service.ts:

import {InjectionToken} from "@angular/core";
export let jQueryToken = new InjectionToken('jQuery'); 

In you module file, add this jQueryToken to provider:

providers:[
{
    provide: jQueryToken,
    useValue: jQuery

}] 

Now @Inject(jQueryToken) and it is ready to use. Let say you want to use inside a component name ExperimentComponent then:

import {Component, Inject, OnInit} from '@angular/core';
import {jQueryToken} from "./common/jquery.service";

@Component({
    selector: 'app-experiment',
    templateUrl: './experiment.component.html',
    styleUrls: ['./experiment.component.css']
})
export class ExperimentComponent implements OnInit {

    constructor(@Inject(jQueryToken) private $: any) {
        $(document).ready(function () {
            alert(' jQuery is working');
        });
    }

    ngOnInit() {
    }

}

Whenever you open ExperimentComponent the alert function will call and pop up the message.

V.Tran
  • 457
  • 1
  • 5
  • 13