如何将jQuery与Angular一起使用?
谁能告诉我,如何将jQuery与Angular一起使用如何将jQuery与Angular一起使用?,jquery,angular,Jquery,Angular,谁能告诉我,如何将jQuery与Angular一起使用 class MyComponent { constructor() { // how to query the DOM element from here? } } 我知道有一些变通方法,比如预先操作DOM元素的类或id,但我希望有一种更干净的方法。与ng1相比,从Angular2使用jQuery是轻而易举的事。如果您使用的是TypeScript,则可以首先引用jQuery TypeScript定义 tsd
class MyComponent {
constructor() {
// how to query the DOM element from here?
}
}
我知道有一些变通方法,比如预先操作DOM元素的类或id,但我希望有一种更干净的方法。与ng1相比,从Angular2使用jQuery是轻而易举的事。如果您使用的是TypeScript,则可以首先引用jQuery TypeScript定义
tsd install jquery --save
or
typings install dt~jquery --global --save
TypescriptDefinitions不是必需的,因为您可以使用any
作为$
或jQuery
在角度组件中,您应该使用@ViewChild()
从模板中引用DOM元素。视图初始化后,您可以使用此对象的nativeElement
属性并传递给jQuery
将$
(或jQuery
)声明为JQueryStatic将为您提供对jQuery的类型化引用
import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
declare var $:JQueryStatic;
@Component({
selector: 'ng-chosen',
template: `<select #selectElem>
<option *ngFor="#item of items" [value]="item" [selected]="item === selectedValue">{{item}} option</option>
</select>
<h4> {{selectedValue}}</h4>`
})
export class NgChosenComponent implements AfterViewInit {
@ViewChild('selectElem') el:ElementRef;
items = ['First', 'Second', 'Third'];
selectedValue = 'Second';
ngAfterViewInit() {
$(this.el.nativeElement)
.chosen()
.on('change', (e, args) => {
this.selectedValue = args.selected;
});
}
}
bootstrap(NgChosenComponent);
您可以实现生命周期挂钩ngAfterViewInit()来添加一些DOM操作
ngAfterViewInit() {
var el:any = elelemtRef.domElement.children[0];
$(el).chosen().on('change', (e, args) => {
_this.selectedValue = args.selected;
});
}
使用路由器时要小心,因为angular2可能会回收视图。。因此,您必须确保DOM元素操作仅在afterViewInit的第一次调用中完成。。(可以使用静态布尔变量执行此操作)
我发现的最有效的方法是在页面/组件构造函数中使用时间为0的setTimeout。这让我们在Angular完成加载所有子组件后的下一个执行周期中运行jQuery。可以使用其他一些组件方法,但我所尝试的方法在setTimeout内运行时效果最好
export class HomePage {
constructor() {
setTimeout(() => {
// run jQuery stuff here
}, 0);
}
}
1) 在组件中访问DOM
import {BrowserDomAdapter } from '@angular/platform-browser/src/browser/browser_adapter';
constructor(el: ElementRef,public zone:NgZone) {
this.el = el.nativeElement;
this.dom = new BrowserDomAdapter();
}
ngOnInit() {
this.dom.setValue(this.el,"Adding some content from ngOnInit");
}
您可以通过以下方式包括jQuery。
2) 在加载angular2之前,将jquery文件包括在index.html中
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- jquery file -->
<script src="js/jquery-2.0.3.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
这对我来说很有用。我用一种更简单的方式来做-首先在控制台中通过npm安装jquery:
npm安装jquery-S
,然后在组件文件中我只写:let$=require('../jquery.min.js')
,它就可以工作了!下面是我的一些代码的完整示例:
import { Component, Input, ElementRef, OnInit } from '@angular/core';
let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
@Component({
selector: 'departments-connections-graph',
templateUrl: './departmentsConnectionsGraph.template.html',
})
export class DepartmentsConnectionsGraph implements OnInit {
rootNode : any;
container: any;
constructor(rootNode: ElementRef) {
this.rootNode = rootNode;
}
ngOnInit() {
this.container = $(this.rootNode.nativeElement).find('.departments-connections-graph')[0];
console.log({ container : this.container});
...
}
}
例如,在teplate中,我有:
<div class="departments-connections-graph">something...</div>
使用
并在index.html中放入:
<script src="assets/js/jquery-2.1.1.js"></script>
这只会在全局范围内初始化jquery一次-这很重要,例如在引导中使用模态窗口…为什么每个人都把它当作火箭科学? 对于需要对静态元素执行一些基本操作的其他人,例如,
body
tag,只需执行以下操作:
script
标记,无论在何处(通过这种方式,您还可以使用IE条件标记为IE9或更小版本加载更低版本的jquery)导出组件
块中,有一个调用代码的函数:$(“body”).addClass(“done”)
Normaly这会导致声明错误,所以在这个.ts文件中的所有导入之后,添加declare var$:any代码>你可以走了李>
现在它变得非常简单,只需在Angular2控制器中声明具有任何类型的jQuery变量即可
declare var jQuery:any;
在import语句之后和component decorator之前添加它
要访问id为X或类为X的任何元素,只需执行以下操作
jQuery("#X or .X").someFunc();
//安装jquerynpm安装jquery——保存
//为jquery安装类型定义typings安装dt~jquery--global--save
//按指定将jquery库添加到构建配置文件中(在“angular cli build.js”文件中)
//运行构建以在构建中添加jquery库ng构建
//添加相对路径配置(在system config.js中)
/**将相对路径映射到URL*/
常量映射:任意={
.....,
.......,
“jquery”:“vendor/jquery/dist”
};代码>
/** User packages configuration. */
const packages: any = {
......,
'jquery':{ main: 'jquery.min',
format: 'global',
defaultExtension: 'js'}};
//在组件文件中导入jquery库
import 'jquery';
下面是我的示例组件的代码snipppet
import { Component } from '@angular/core';
import 'jquery';
@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
list:Array<number> = [90,98,56,90];
title = 'app works!';
isNumber:boolean = jQuery.isNumeric(89)
constructor(){}
}
import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery'; // I faced issue in using jquery's popover
Or
declare var $: any; // declaring jquery in this way solved the problem
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
}
jQueryExampleModal() { // to show a modal with dummyId
$('#dummyId').modal('show');
}
从'@angular/core'导入{Component};
导入“jquery”;
@组成部分({
moduleId:module.id,
选择器:'应用程序根',
templateUrl:'app.component.html',
样式URL:['app.component.css']
})
导出类AppComponent{
列表:数组=[90,98,56,90];
title='appworks!';
isNumber:boolean=jQuery.isNumeric(89)
构造函数(){}
}
因为我是个笨蛋,所以我觉得有一些工作代码会很好
另外,Angular2打字版本是$
,所以最常见的答案并没有给我一个干净的编译
以下是我需要完成的步骤:
index.html
<head>
...
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
...
</head>
<script type="text/javascript" src="assets/js/jquery-2.1.1.min.js"></script>
只要写
declare var $:any;
在所有导入部分之后,您可以使用jQuery并在index.html页面中包含jQuery库
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
它对我有用这就是对我有用的东西
第一步-第一件事
第2步-导入
#更新-2017年2月
最近,我用ES6
而不是typescript
编写代码,并且能够导入,而无需*在导入语句中作为$
。这就是它现在的样子:
import $ from 'jquery';
//
$('#elemId').width();
祝你好运。请按照以下简单步骤操作。这对我有用。让我们从一个新的angular 2应用程序开始,以避免任何混乱。我用的是Angular cli。因此,如果您还没有安装,请安装它。
步骤1:创建演示angular 2应用程序
ng new jquery-demo
你可以用任何名字。现在,通过在cmd下运行来检查它是否工作。(现在,如果不使用cd命令,请确保指向“jquery demo”)
您将在浏览器上看到“应用程序工作!”
步骤2:安装Bower(一个web包管理器)
在cli上运行此命令(如果不使用cd命令,请确保指向“jquery演示”:
现在,在成功安装bower之后,使用以下命令创建一个“bower.json”文件:
bower init
它将要求输入,如果需要默认值,只需按enter键,然后在最后键入“是”,然后询问“看起来不错?”
现在您可以在文件夹“jquerydemo”中看到一个新文件(bower.json)。你可以在上找到更多信息
St
declare var $:any;
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
// In the console
// First install jQuery
npm install --save jquery
// and jQuery Definition
npm install -D @types/jquery
// Now, within any of the app files (ES2015 style)
import * as $ from 'jquery';
//
$('#elemId').width();
// OR
// CommonJS style - working with "require"
import $ = require('jquery')
//
$('#elemId').width();
import $ from 'jquery';
//
$('#elemId').width();
ng new jquery-demo
ng serve
npm i -g bower --save
bower init
bower install jquery --save
"scripts": ["../bower_components/jquery/dist/jquery.min.js"
]
<h1>
{{title}}
</h1>
<p>If you click on me, I will disappear.</p>
import { Component, AfterViewInit } from '@angular/core';
declare var $:any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
ngAfterViewInit(){
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
}
}
import { InjectionToken } from '@angular/core';
export const JQ_TOKEN = new InjectionToken('jQuery');
export function jQueryFactory() {
return window['jQuery'];
}
export const JQUERY_PROVIDER = [
{ provide: JQ_TOKEN, useFactory: jQueryFactory },
];
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { JQ_TOKEN } from './jQuery.service';
declare let jQuery: Object;
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent
],
providers: [
{ provide: JQ_TOKEN, useValue: jQuery }
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Component, Inject } from '@angular/core';
import { JQ_TOKEN } from './jQuery.service';
@Component({
selector: "selector",
templateUrl: 'somefile.html'
})
export class SomeComponent {
constructor( @Inject(JQ_TOKEN) private $: any) { }
somefunction() {
this.$('...').doSomething();
}
}
import { Component } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
console.log($(window)); // jquery is accessible
}
<script type="text/javascript" src="assets/js/jquery-2.1.1.min.js"></script>
declare var $: any;
@Component({
selector: 'home',
templateUrl: './my.component.html',
})
export class MyComponent implements OnInit {
...
$("#myselector").style="display: none;";
}
import { Component } from '@angular/core';
import $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(){
console.log($('body'));
}
}
import * as $ from 'jquery';
// in Angular v2 it is OpaqueToken (I am on Angular v5)
import { InjectionToken } from '@angular/core';
export const JQUERY_TOKEN = new InjectionToken('jQuery');
import { JQUERY_TOKEN } from './services/jQuery.service';
declare const jQuery: Object;
providers: [
{ provide: JQUERY_TOKEN, useValue: jQuery },
]
import { Component, Inject } from '@angular/core';
export class MySuperDuperComponent {
constructor(@Inject(JQUERY_TOKEN) private $: any) {}
someEventHandler() {
this.$('#my-element').css('display', 'none');
}
}
import 'jquery'
import 'popper.js'
import 'bootstrap'
@import "~bootstrap/dist/css/bootstrap.min.css";
npm install jquery --save
"scripts": [ "node_modules/jquery/dist/jquery.min.js" ] // copy relative path of node_modules>jquery>dist>jquery.min.js to avoid path error
import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery'; // I faced issue in using jquery's popover
Or
declare var $: any; // declaring jquery in this way solved the problem
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
}
jQueryExampleModal() { // to show a modal with dummyId
$('#dummyId').modal('show');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="button" value="Add New" (click)="ShowForm();">
<div class="container">
//-----.HideMe{display:none;} is a css class----//
<div id="PriceForm" class="HideMe">
<app-pricedetails></app-pricedetails>
</div>
<app-pricemng></app-pricemng>
</div>
declare var $: any;
ShowForm(){
$('#PriceForm').removeClass('HideMe');
}
npm install jquery — save
"scripts": [ "../node_modules/jquery/dist/jquery.min.js" ]
import * as $ from 'jquery';
(or)
declare var $: any;
import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Look jQuery Animation working in action!';
public ngOnInit()
{
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({left: '100px'}, "slow");
div.animate({fontSize: '5em'}, "slow");
});
});
}
}