How to import jQuery to Angular2 TypeScript projects?
Asked Answered
S

7

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?

Sheply answered 15/9, 2016 at 13:3 Comment(7)
angular already provide basic functionality of jquery instead of importing jquery as it will cause problem in long runPitiless
How to use it? I would use .dropdown() method for example...Sheply
I'm not aware of that specific functionality.Alonzo
Ok, anyway how can i use the builtin jQuery library?Sheply
.dropdown() is not a function of jquery. Are u using bootstrap.js ? If u are using it then you have to use jquery or just switch to ng-bootstrap which is bootstrap wriiten for angular by angular team search google.Pitiless
I see it from here: plnkr.co/edit/MMNWGh. It is a jQuery plugin.Sheply
Follow these simple steps here: https://mcmap.net/q/86227/-how-to-use-jquery-with-angularPickwickian
V
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 $!

Vladimar answered 12/4, 2017 at 18:18 Comment(2)
Yes, but no intellisense ;(Exhibitionist
@Exhibitionist I did it and i have intellisense. However you got to add jquery to types array in tsconfig.json.Frangipani
S
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.

Swam answered 7/9, 2017 at 11:6 Comment(2)
You also have to make sure you import into Component, use: import * as $ from "jquery";Massive
No obviously needed.. if you work with backbone you'll maybe need import * as $ from 'backbone';Muncy
V
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');
    }
  }
}
Validate answered 4/2, 2017 at 19:10 Comment(1)
OpaqueToken is deprecated though, but you can simply change it with the InjectionToken as described here thecodegarden.net/…Whitmer
A
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");
        });
    }
}
Alonzo answered 15/9, 2016 at 13:29 Comment(8)
Shoud i write the following line in the systemjs.config.js} file? 'jquery': 'typings/global/jquery/index.d.ts'Sheply
No, no need to write anything in the SystemJS config. Just add a <script> tag to your index.html, where you load jquery.js. Then add the reference to the components or directives, where you need it.Alonzo
Sorry, i'm afraid i don't figure out how it works. Can you show me an example or some code?Sheply
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?Sheply
Please, have a look at this: 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?Sheply
this is the oldschool way of doing it.Neurophysiology
You can do the same this way - I'll update my answer for your plugin "request".Alonzo
Not gonna lie - this version of using external JS files will save you a lot of headaches with SystemJS or any packaging tool.Alonzo
N
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.

Neurophysiology answered 15/9, 2016 at 13:13 Comment(10)
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?Sheply
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 typeNeurophysiology
If i import with scripts html tag, i cannot use jQuery for writing code in my Angular2 directives/components.Sheply
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.Neurophysiology
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?Sheply
start with "import $ from 'jquery';" and you should see the intellisense off the "$" working. Test with that first.Neurophysiology
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.Sheply
search solution for "declare module "jquery"". Your typings file should have this.Neurophysiology
Why import * as $ from 'jquery' does work? Anyway, how to make it work even with dropdown jQuery plugin?Sheply
Resolved after installing. npm install @types/jquery --saveBushweller
A
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!");
    };
});
Artefact answered 15/9, 2016 at 18:29 Comment(0)
I
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.

Intermingle answered 10/8, 2017 at 8:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.