谁能告诉我,如何将 jQuery 与 Angular 一起使用?
class MyComponent {
constructor() {
// how to query the DOM element from here?
}
}
我知道有一些解决方法,例如预先操作 DOM 元素的 class 或 id,但我希望有一种更简洁的方法。
最佳答案
与 ng1 相比,在 Angular2 中使用 jQuery 轻而易举。如果您使用的是 TypeScript,您可以先引用 jQuery typescript 定义。
tsd install jquery --save
or
typings install dt~jquery --global --save
不需要 TypescriptDefinitions,因为您可以使用 any
作为 $
或 jQuery
在您的 Angular 组件中,您应该使用 @ViewChild()
从模板中引用 DOM 元素 在 View 初始化后,您可以使用该对象的 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);
这个例子在 plunker 上可用:http://plnkr.co/edit/Nq9LnK?p=preview
tslint 会提示 chosen
不是 $ 上的属性,要解决这个问题,您可以在自定义 *.d.ts 文件中向 JQuery 接口(interface)添加定义
interface JQuery {
chosen(options?:any):JQuery;
}
关于jquery - 如何在 Angular 中使用 jQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30623825/