누구든지 Angular 와 함께 jQuery 를 사용하는 방법을 말해 줄 수 있습니까 ?
class MyComponent {
constructor() {
// how to query the DOM element from here?
}
}
DOM 요소 의 클래스 또는 ID 를 미리 조작하는 것과 같은 해결 방법이 있다는 것을 알고 있지만 더 깨끗한 방법을 원합니다.
Angular2에서 jQuery를 사용하는 것은 ng1에 비해 매우 쉽습니다. TypeScript를 사용하는 경우 먼저 jQuery typescript 정의를 참조 할 수 있습니다.
tsd install jquery --save
or
typings install dt~jquery --global --save
또는 any
유형으로 사용할 수 있으므로 TypescriptDefinitions는 필요하지 않습니다.$
jQuery
각도 구성 요소에서 템플릿에서 DOM 요소를 참조해야 @ViewChild()
합니다.보기가 초기화 된 후이 nativeElement
개체 의 속성을 사용하고 jQuery에 전달할 수 있습니다.
JQueryStatic으로 선언 $
(또는 jQuery
)하면 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 JQuery {
chosen(options?:any):JQuery;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다