怎样在angular 4+中使用jquery?
在angular 4+中使用jquery是一件很轻松的事!
1,先引用jQuery的typescript定义
tsd install jquery --save or typings install dt~jquery --global --save
2,在需要使用jQuery的地方,声明使用Jquery
import {bootstrap} from '@angular/platform-browser-dynamic'; import {Component,ViewChild,ElementRef,AfterViewInit} from '@angular/core'; declare var $:JQueryStatic; // 声明jquery @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) // 使用jquery .chosen() .on('change',(e,args) => { this.selectedValue = args.selected; }); } } bootstrap(NgChosenComponent);
class MyComponent { constructor() { // 怎样在这个地方使用jquery 获取dom元素? } }
在angular 4+中使用jquery是一件很轻松的事!
1,先引用jQuery的typescript定义
tsd install jquery --save or typings install dt~jquery --global --save
2,在需要使用jQuery的地方,声明使用Jquery
import {bootstrap} from '@angular/platform-browser-dynamic'; import {Component,ViewChild,ElementRef,AfterViewInit} from '@angular/core'; declare var $:JQueryStatic; // 声明jquery @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) // 使用jquery .chosen() .on('change',(e,args) => { this.selectedValue = args.selected; }); } } bootstrap(NgChosenComponent);