如何在角度2中使用jQuery和javascript
import {Component, ElementRef, OnInit} from 'angular2/core'; declare var jQuery:any; @Component({ selector: 'jquery-integration', templateUrl: './components/jquery-integration/jquery-integration.html' }) export class JqueryIntegration implements OnInit { elementRef: ElementRef; constructor(elementRef: ElementRef) { this.elementRef = elementRef; } ngOnInit() { jQuery(this.elementRef.nativeElement).draggable({ containment:'#draggable-parent' }); } }
jQuery可以像Angular2一样在Typeular中使用吗? 如何在Angular2中使用jQuery和JavaScript?
在我看来:如果你做得对,如果你把它保持在最低限度,你就应该坚持下去。
- 在项目中安装jQuery Typings:tsd install jQuery
- 使用脚本标记(或其他加载器…)加载jQuery
- 使用Angular 2 Directive包装任何jQuery插件
例:
@Directive({ selector: "[sm-dropdown]" }) export class SMDropdown { constructor(el: ElementRef) { jQuery(el.nativeElement).dropdown(); } }
考虑一下这个Plunker:
https://plnkr.co/edit/MMNWGh?p=preview
别:
- 不要将它用于DOM操作,有Angular方式……
- 不要用它来进行AJAX调用,有Angular方式……
- 不要用它来制作动画,ngAnimation即将到来……
安装JQuery打字稿库后,以这种方式引用它
///
然后进行必要的import
import {Component, AfterViewInit} from 'angular2/core';
现在写课
@Component({ selector: 'my-app', templateUrl: 'app/html/app.component.html' }) export class AppComponent implements AfterViewInit { ngAfterViewInit() { // Your jQuery code goes here $('#here').text("HALLO! ^_^"); } }
我该怎么做才能解决这个问题:
对于库不支持@types/
和库需要在加载文件时加载(平均库需要在文件的脚本标签中添加)
- 运行
npm install jquery --save
-
在
angular-cli.json
scripts
或styles
中添加js / css文件"scripts": ["../node_modules/path to file", "./assets/path to file"]
对于库支持的@types/
,只需运行npm install @types/jquery --save-dev
要使用该库,请添加declare var jQuery: any;
在注释之前@Directive
或@Component
想要使用lib
P / S:我在我的项目中使用了带有webpack
angular-cli
,可能与systemjs
不同
你必须告诉你在哪里可以找到你的jQuery typeScript定义。 这可以在typings.d.ts文件中完成,你可以在这里输入你的类型:
///
或者您可以通过节点安装打字,让您的配置自动加载。 这就是angular-cli所做的。
之后,要在Angular2中使用jQuery,您必须了解一个基本机制。 Angular2有自己的dom表示,jQuery操纵这个dom。 这就是人们说“不要在Angular2中使用jQuery”的原因。 这是不对的。 Angular2为此问题提供了解决方案。 它称之为ControlValueAccessor 。 这样做的目的是在你的jQuery插件修改DOM时提醒角度,并且在修改DOM时让angular通知你的插件。
让我通过日期选择器日历的例子来解释这一点。
import { Directive, ElementRef, OnInit, AfterViewInit, Input, forwardRef, OnDestroy } from '@angular/core'; import { Moment } from 'moment'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; const DATE_PICKER_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => FnCalendarDirective), multi: true, }; @Directive({ selector: '[fn-calendar]', providers: [DATE_PICKER_VALUE_ACCESSOR], }) export class FnCalendarDirective implements OnInit, AfterViewInit, ControlValueAccessor, OnDestroy { @Input() format: string = 'DD/MM/YYYY HH:mm'; @Input() showClose: boolean = true; @Input() sideBySide: boolean = false; @Input() ngModel; private onTouched = () => { }; private onChange: (value: string) => void = () => { }; constructor(private el: ElementRef) { } ngOnInit() { } ngAfterViewInit() { $(this.el.nativeElement).datetimepicker({ locale: 'fr', sideBySide: this.sideBySide, format: this.format, showClose: this.showClose, icons: { time: 'fa fa-clock-o', date: 'fa fa-calendar', up: 'fa fa-chevron-up', down: 'fa fa-chevron-down', previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-bullseye', clear: 'fa fa-trash', close: 'fa fa-times' }, }).on('dp.change', event => { let date: Moment = ((event).date); if (date) { let value = date.format(this.format); this.onChange(value); } }); this.writeValue(this.ngModel); } writeValue(date: string) { $(this.el.nativeElement).datetimepicker().data('DateTimePicker').date(date); } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouched = fn; } ngOnDestroy() { $(this.el.nativeElement).datetimepicker().data('DateTimePicker').destroy(); } }
这里重要的是writeValue方法,让Angular2通知你的jquery插件正在产生一个变化。 和registerOnChange,让你通知Angular2你的插件改变了DOM。
总之,使用jQuery的关键是将jQuery插件包装在指令中并实现CustomValueAccesor来处理插件和Angular2之间的通信。
要查找输入法,可以使用DefinitlyTyped GitHub,它是许多js库中的输入法定义的存储库。
[1]: http://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html
你不应该以任何价格将Angular组件与jQuery联系起来
- 使用
标记加载jQuery。
- 添加jQuery文档就绪处理程序。
$('document')。ready((function($){ return function(){ // DOM已准备好,$是对jQuery的引用 //现在是时候用$完成事情了 }; })(jQuery的));
优点 :
- Angular组件没有jQuery依赖。
- 更容易测试这样的组件,维护和重用。
- jQuery代码是孤立的。
但是,如果需要在组件内部使用jQuery,请使用服务或指令。
如果在加载部分视图时遇到问题,请在文档节点和jQuery窗口加载处理程序上使用jQuery事件处理程序。
我们可以使用如下:
var jq=require('./jquery.min.js'); ..... export class AppComponent{ ngOnInit(){ jq(); console.log($('body')) // show:[body, prevObject: r.fn.init[1]] //ok!normal operation! } }