可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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 $!
回答2:
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.
回答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>×</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');
}
}
}
回答4:
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");
});
}
}
回答5:
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.
回答6:
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!");
};
});
回答7:
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.