如何在 Angular 中使用 jQuery? [英] How to use jQuery with Angular?
问题描述
谁能告诉我,如何将 jQuery 与 Angular 一起使用?
Can anyone tell me, how to use jQuery with Angular?
class MyComponent {
constructor() {
// how to query the DOM element from here?
}
}
我知道有一些变通方法,例如预先操作 DOM 元素的 class 或 id,但我希望有一种更简洁的方法.
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 typescript 定义.
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
TypescriptDefinitions are not required since you could just use any
as the type for $
or jQuery
在你的 Angular 组件中,你应该使用 @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屋!