How to import jQuery to Angular2 TypeScript projects?
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 $!
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.
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>×</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'); } }}