[jquery] Angular와 함께 jQuery를 사용하는 방법은 무엇입니까?

누구든지 Angular 와 함께 jQuery 를 사용하는 방법을 말해 줄 수 있습니까 ?

class MyComponent {
    constructor() {
        // how to query the DOM element from here?
    }
}

DOM 요소 의 클래스 또는 ID 를 미리 조작하는 것과 같은 해결 방법이 있다는 것을 알고 있지만 더 깔끔한 방법을 원합니다.



답변

Angular2에서 jQuery를 사용하는 것은 ng1과 비교하면 쉽습니다. TypeScript를 사용하는 경우 먼저 jQuery 유형 스크립트 정의를 참조 할 수 있습니다.

tsd install jquery --save
or
typings install dt~jquery --global --save

당신은 그냥 사용할 수 있기 때문에 TypescriptDefinitions이 필요하지 않습니다 any에 대한 유형으로 $jQuery

각도 구성 요소 @ViewChild()에서는 뷰가 초기화 된 후이 nativeElement객체 의 속성을 사용하여 jQuery에 전달할 수 있는 템플릿에서 DOM 요소를 참조해야합니다 .

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;
}    


답변

왜 모두가 로켓 과학을 만드는가? 정적 요소 (예 : body태그)에 대한 기본 작업을 수행해야하는 다른 사람 은 다음과 같이하십시오.

  1. index.html에서 scriptjquery lib의 경로가있는 태그를 추가 하면 위치는 중요하지 않습니다 (이 방법으로 IE 조건부 태그를 사용하여 IE9 이하의 jquery 하위 버전을로드 할 수도 있습니다).
  2. 당신에 export component: 블록 코드를 호출하는 기능이 $("body").addClass("done");추가 Normaly이 그래서 그냥이 .TS 파일의 모든 수입 후, 선언의 오류가 발생 declare var $:any;하고 당신은 갈 수 있습니다!

답변

이것이 나를 위해 일한 것입니다.

1 단계-첫 번째 사항

// In the console
// First install jQuery
npm install --save jquery
// and jQuery Definition
npm install -D @types/jquery

2 단계-수입

// 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();

# 업데이트- Feb - 2017

최근에, 나는에 코드를 쓰고 있어요 ES6대신 typescript하고 수 있어요 import없이 * as $에서 import statement. 이것이 지금 보이는 모습입니다 :

import $ from 'jquery';
//
$('#elemId').width();

행운을 빕니다.


답변

이제는 매우 쉬워졌습니다. Angular2 컨트롤러 내부의 모든 유형으로 jQuery 변수를 선언하면됩니다.

declare var jQuery:any;

import 문 직후와 구성 요소 데코레이터 앞에 이것을 추가하십시오.

ID X 또는 클래스 X를 가진 요소에 액세스하려면 수행해야합니다.

jQuery("#X or .X").someFunc();


답변

간단한 방법 :

1. 스크립트 포함

index.html

<script type="text/javascript" src="assets/js/jquery-2.1.1.min.js"></script>

2. 선언

my.component.ts

declare var $: any;

3. 사용

@Component({
  selector: 'home',
  templateUrl: './my.component.html',
})
export class MyComponent implements OnInit {
 ...
  $("#myselector").style="display: none;";
}


답변

이 간단한 단계를 따르십시오. 그것은 나를 위해 일했다. 혼란을 피하기 위해 새로운 각도 2 앱으로 시작할 수 있습니다. Angular cli를 사용하고 있습니다. 아직 설치하지 않은 경우 설치하십시오.
https://cli.angular.io/

1 단계 : 데모 각도 2 앱 만들기

ng new jquery-demo

어떤 이름이든 사용할 수 있습니다. 이제 cmd 아래에서 실행하여 작동하는지 확인하십시오 (이제 cd 명령을 사용하지 않으면 ‘jquery-demo’을 가리키고 있는지 확인하십시오)

ng serve

“앱이 작동합니다!”가 표시됩니다 브라우저에서.

2 단계 : Bower 설치 (웹용 패키지 관리자)

cli에서이 명령을 실행하십시오 (cd command를 사용하지 않으면 ‘jquery-demo’를 가리키고 있는지 확인하십시오).

npm i -g bower --save

이제 bower를 성공적으로 설치 한 후 아래 명령을 사용하여 ‘bower.json’파일을 작성하십시오.

bower init

입력을 요구할 것입니다. 기본값을 원하면 Enter 키를 누르십시오. 그리고 “Looks good?”이라고 물을 때 “Yes”를 입력하십시오.

이제 “jquery-demo”폴더에 새 파일 (bower.json)이 표시됩니다. https://bower.io/에서 자세한 정보를 찾을 수 있습니다.

3 단계 : jquery 설치

이 명령을 실행

bower install jquery --save

jquery 설치 폴더가 포함될 새 폴더 (bower_components)를 만듭니다. 이제 ‘bower_components’폴더에 jquery가 설치되었습니다.

4 단계 : ‘angular-cli.json’파일에 jquery 위치 추가

‘angular-cli.json’파일 ( ‘jquery-demo’폴더에 있음)을 열고 “scripts”에 jquery 위치를 추가하십시오. 다음과 같이 보일 것입니다 :

"scripts": ["../bower_components/jquery/dist/jquery.min.js"
              ]

5 단계 : 테스트를위한 간단한 jquery 코드 작성

‘app.component.html’파일을 열고 간단한 코드 행을 추가하십시오. 파일은 다음과 같습니다.

<h1>
  {{title}}
</h1>
<p>If you click on me, I will disappear.</p>

이제 ‘app.component.ts’파일을 열고 ‘p’태그에 대한 jquery 변수 선언 및 코드를 추가하십시오. 라이프 사이클 후크 ngAfterViewInit ()도 사용해야합니다. 변경 후 파일은 다음과 같습니다.

import { Component, AfterViewInit } from '@angular/core';
declare var $:any;

@Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css']
})
export class AppComponent {
     title = 'app works!';

     ngAfterViewInit(){
           $(document).ready(function(){
             $("p").click(function(){
             $(this).hide();
             });
           });
     }
}

이제 ‘ng serve’명령을 사용하여 각도 2 앱을 실행하고 테스트하십시오. 작동해야합니다.


답변

라이프 사이클 후크 ngAfterViewInit () 를 구현하여 DOM 조작을 추가 할 수 있습니다.

ngAfterViewInit() {
            var el:any = elelemtRef.domElement.children[0];
            $(el).chosen().on('change', (e, args) => {
                _this.selectedValue = args.selected;
            });
}

angular2는 뷰를 재활용 할 수 있으므로 라우터를 사용할 때주의하십시오. 따라서 DOM 요소 조작은 afterViewInit의 첫 번째 호출에서만 수행되어야합니다. (정적 부울 변수를 사용하여 그렇게 할 수 있습니다)

class Component {
    let static chosenInitialized  : boolean = false;
    ngAfterViewInit() {
        if (!Component.chosenInitialized) {
            var el:any = elelemtRef.domElement.children[0];
            $(el).chosen().on('change', (e, args) => {
                _this.selectedValue = args.selected;
            });
            Component.chosenInitialized = true;
        }
    }
}