谁能告诉我,如何使用jQuery和Angular?
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,因为您可以只使用或
在angular组件中,您应该使用从模板引用一个DOM元素。在视图初始化之后,您可以使用该对象的
将(或
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会抱怨
interface JQuery {
chosen(options?:any):JQuery;
}
为什么大家都把它当成火箭科学?对于其他需要对静态元素(例如
正常时,这会导致声明错误,因此在此。ts文件中导入所有内容后,添加,您就可以使用GO/LI>了
这对我很管用。
// 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();
祝你好运。