Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import jQuery to Angular2 TypeScript projects?

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?

like image 494
smartmouse Avatar asked Sep 15 '16 13:09

smartmouse


People also ask

Can jQuery be used in typescript?

JQuery is one of the most popular JavaScript libraries which exposes a lot of usable APIs for JavaScript developers. It's an integration with Typescript that may do wonders for you.

Can I use jQuery in Angular?

jQuery is a small yet feature-rich powerful javascript library that helps to manipulate the HTML DOM with less javascript code. We can use jQuery with Angular. There are some situations you come across while building Angular apps that it's absolutely necessary to use a library like jQuery to get something done.

Can we use jQuery in Angular 6?

In the above code, we first import jquery to use its component. We then need to implement ngOnInit Lifecycle Hook which can be imported from Angular Core. We can write jQuery code inside the method ngOnInit, To add the action to the button we created in app. component.

Why jQuery is not used in Angular?

Selectors and events are usually solved by libraries like React and Angular, so you don't need jQuery to help with browser compability and API differences.


3 Answers

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

like image 174
Chinmay Avatar answered Sep 27 '22 15:09

Chinmay


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.

like image 31
Sheo Sagar Avatar answered Sep 27 '22 17:09

Sheo Sagar


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');
    }
  }
}
like image 41
user1089766 Avatar answered Sep 27 '22 16:09

user1089766