如何在Angular中使用jQuery? [英] How to use jQuery with Angular?
问题描述
任何人都可以告诉我,如何在 Angular 中使用 jQuery 吗?
Can anyone tell me, how to use jQuery with Angular?
class MyComponent {
constructor() {
// how to query the DOM element from here?
}
}
我知道有一些变通方法,例如预先处理DOM元素的 class 或 id ,但我希望有一种更清洁的方法. /p>
I'm aware there are workarounds like manipulating the class or id of the DOM element upfront, but I'm hoping for a cleaner way of doing it.
推荐答案
与ng1相比,使用来自Angular2的jQuery轻而易举.如果您使用的是TypeScript,则可以先引用jQuery打字稿定义.
Using jQuery from Angular2 is a breeze compared to ng1. If you are using TypeScript you could first reference jQuery typescript definition.
tsd install jquery --save
or
typings install dt~jquery --global --save
不需要
TypescriptDefinitions,因为您可以将any
用作$
或jQuery
在角度组件中,应使用@ViewChild()
从模板引用DOM元素.初始化视图后,可以使用此对象的nativeElement
属性,并将其传递给jQuery.
In your angular component you should reference a DOM element from the template using @ViewChild()
After the view has been initialized you can use the nativeElement
property of this object and pass to jQuery.
将$
(或jQuery
)声明为JQueryStatic将为您提供对jQuery的类型化引用.
Declaring $
(or jQuery
) as JQueryStatic will give you a typed reference to 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);
此示例可在plunker上使用: http://plnkr.co/edit/Nq9LnK?p=preview
This example is available on plunker: http://plnkr.co/edit/Nq9LnK?p=preview
tslint将抱怨chosen
不是$的属性,要解决此问题,您可以在自定义* .d.ts文件的JQuery接口中添加一个定义
tslint will complain about chosen
not being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file
interface JQuery {
chosen(options?:any):JQuery;
}
这篇关于如何在Angular中使用jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!