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?

7
  • angular already provide basic functionality of jquery instead of importing jquery as it will cause problem in long run Commented Sep 15, 2016 at 13:27
  • 1
    How to use it? I would use .dropdown() method for example... Commented Sep 15, 2016 at 13:29
  • I'm not aware of that specific functionality. Commented Sep 15, 2016 at 13:31
  • Ok, anyway how can i use the builtin jQuery library? Commented Sep 15, 2016 at 13:33
  • .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. Commented Sep 15, 2016 at 13:33

7 Answers 7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but no intellisense ;(
@SharpNoiZy I did it and i have intellisense. However you got to add jquery to types array in tsconfig.json.
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.

2 Comments

You also have to make sure you import into Component, use: import * as $ from "jquery";
No obviously needed.. if you work with backbone you'll maybe need import * as $ from 'backbone';
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');
    }
  }
}

1 Comment

OpaqueToken is deprecated though, but you can simply change it with the InjectionToken as described here thecodegarden.net/…
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");
        });
    }
}

8 Comments

Shoud i write the following line in the systemjs.config.js} file? 'jquery': 'typings/global/jquery/index.d.ts'
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.
Sorry, i'm afraid i don't figure out how it works. Can you show me an example or some code?
this is the oldschool way of doing it.
Not gonna lie - this version of using external JS files will save you a lot of headaches with SystemJS or any packaging tool.
|
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.

10 Comments

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?
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
If i import with scripts html tag, i cannot use jQuery for writing code in my Angular2 directives/components.
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.
Why import * as $ from 'jquery' does work? Anyway, how to make it work even with dropdown jQuery plugin?
|
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!");
    };
});

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.