복붙노트

[JQUERY] 어떻게 각도와 jQuery를 사용 하는가?

JQUERY

어떻게 각도와 jQuery를 사용 하는가?

해결법


  1. 1.Angular2에서 jQuery를 사용하여 NG1에 비해 바람이다. 당신이 타이프 라이터를 사용하는 경우는 첫 번째 정의 타이프 라이터 jQuery를 참조 할 수 있습니다.

    Angular2에서 jQuery를 사용하여 NG1에 비해 바람이다. 당신이 타이프 라이터를 사용하는 경우는 첫 번째 정의 타이프 라이터 jQuery를 참조 할 수 있습니다.

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

    당신은 단지 $ jQuery와의 형태로서 하나를 사용할 수 있기 때문에 TypescriptDefinitions가 필요하지 않습니다

    당신의 각 구성 요소에서 당신은보기 당신이이 객체의 nativeElement 속성을 사용 및 jQuery를에 전달할 수있는 초기화 한 후 @ViewChild ()를 사용하여 템플릿에서 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이 선택한 $의 속성 없다는 불평 것입니다, 당신은 사용자 정의 * .d.ts 파일에서 JQuery와 인터페이스에 정의를 추가 할 수 있습니다이 문제를 해결하려면

    interface JQuery {
        chosen(options?:any):JQuery;
    }    
    

  2. 2.왜 사람들은 로켓 과학을하고있다? 필요로 다른 사람이 정적 요소를 몇 가지 기본적인 물건을 할 경우, 예를 들어, body 태그, 그냥 이렇게 :

    왜 사람들은 로켓 과학을하고있다? 필요로 다른 사람이 정적 요소를 몇 가지 기본적인 물건을 할 경우, 예를 들어, body 태그, 그냥 이렇게 :


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

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

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

    최근에, 내가 대신 타이프의 ES6으로 코드를 작성하고, import 문에 $로 *없이 가져올 수 있어요 있어요. 이것은 지금 모습입니다 :

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

    행운을 빕니다.


  4. 4.지금은 매우 쉽게되고있다, 당신은 단순히 Angular2 컨트롤러 내부의 모든 유형의 jQuery 변수를 선언하여 작업을 수행 할 수 있습니다.

    지금은 매우 쉽게되고있다, 당신은 단순히 Angular2 컨트롤러 내부의 모든 유형의 jQuery 변수를 선언하여 작업을 수행 할 수 있습니다.

    declare var jQuery:any;
    

    단지 import 문 후 구성 요소를 장식하기 전에이 작업을 추가합니다.

    아이디 X 또는 클래스 X와 함께 모든 요소에 액세스하려면 당신은해야 할

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

  5. 5.간단한 방법 :

    간단한 방법 :

    스크립트가 포함 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;";
    }
    

  6. 6.다음의 간단한 단계를 따르십시오. 그것은 나를 위해 일했습니다. 혼란을 피하기 위해 새로운 각도이 응용 프로그램과 함께 시작할 수 있습니다. 나는 각도 CLI를 사용하고 있습니다. 당신은 이미이없는 경우에 따라서, 설치합니다. https://cli.angular.io/

    다음의 간단한 단계를 따르십시오. 그것은 나를 위해 일했습니다. 혼란을 피하기 위해 새로운 각도이 응용 프로그램과 함께 시작할 수 있습니다. 나는 각도 CLI를 사용하고 있습니다. 당신은 이미이없는 경우에 따라서, 설치합니다. https://cli.angular.io/

    1 단계 : 데모 각 2 응용 프로그램을 만들기

    ng new jquery-demo
    

    당신은 어떤 이름을 사용할 수 있습니다. 이 cmd를 아래 실행하여 작동하는지 지금 확인. (이제, 당신이 cd 명령을 사용하지 않을 경우 'JQuery와 - 데모'를 가리키고 있는지 확인)

    ng serve
    

    당신은 "응용 프로그램이 작동합니다!"를 참조합니다 브라우저에서.

    2 단계 : 정자 (웹을위한 패키지 관리자)를 설치

    CLI에서이 명령을 실행 (당신이 cd 명령을 사용하지 않을 경우 'JQuery와 - 데모'를 가리키고 있는지 확인)

    npm i -g bower --save
    

    지금은 정자를 성공적으로 설치 한 후, 명령 아래 사용하여 'bower.json'파일을 만듭니다

    bower init
    

    그것은 당신이 기본 값을 원하는 경우 키를 눌러서 모든 입력하고 종료 유형 "예"에 그것을 물어 볼게요 때, 입력을 요청할 것 "외모에 좋은?"

    지금 당신은 폴더 "JQuery와 - 데모"에 새 파일 (bower.json)을 볼 수 있습니다. 당신은 https://bower.io/에 대한 자세한 정보를 찾을 수 있습니다

    3 단계 : jQuery를 설치

    이 명령을 실행

    bower install jquery --save
    

    그것은 JQuery와 설치 폴더를 포함하는 새로운 폴더 (bower_components)를 생성합니다. 이제 JQuery와 'bower_components'폴더에 설치했습니다.

    4 단계 : '각-cli.json'파일에 JQuery와 위치 추가

    열기 '각도 - cli.json'파일 ( 'JQuery와 - 데모'폴더에) 및 "스크립트"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'를 사용하여 명령 및 테스트 그것이하여 각 2 응용 프로그램을 실행합니다. 그것은 작동합니다.


  7. 7.당신은 몇 가지 DOM 조작을 추가 라이프 사이클 후크 ngAfterViewInit ()를 구현할 수 있습니다

    당신은 몇 가지 DOM 조작을 추가 라이프 사이클 후크 ngAfterViewInit ()를 구현할 수 있습니다

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

  8. 8.나는 간단한 방법으로 그것을 할 - 최초의 콘솔에서 NPM에 의해 jQuery를 설치 : 설치 NPM JQuery와 -S 다음 구성 요소 파일에 난 그냥 쓰기 : 및 작동 ( '... / jquery.min.js') $ =이 필요하자! 일부 내 코드에서 전체 예제 여기 :

    나는 간단한 방법으로 그것을 할 - 최초의 콘솔에서 NPM에 의해 jQuery를 설치 : 설치 NPM JQuery와 -S 다음 구성 요소 파일에 난 그냥 쓰기 : 및 작동 ( '... / jquery.min.js') $ =이 필요하자! 일부 내 코드에서 전체 예제 여기 :

    import { Component, Input, ElementRef, OnInit } from '@angular/core';
    let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
    
    @Component({
        selector: 'departments-connections-graph',
        templateUrl: './departmentsConnectionsGraph.template.html',
    })
    
    export class DepartmentsConnectionsGraph implements OnInit {
        rootNode : any;
        container: any;
    
        constructor(rootNode: ElementRef) {
          this.rootNode = rootNode; 
        }
    
        ngOnInit() {
          this.container = $(this.rootNode.nativeElement).find('.departments-connections-graph')[0];
          console.log({ container : this.container});
          ...
        }
    }
    

    템플릿에서 나는 예를 들어 있습니다 :

    <div class="departments-connections-graph">something...</div>
    

    편집하다

    또한 사용하는 대신 :

    let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
    

    사용하다

    declare var $: any;
    

    당신의 index.html을 넣어 :

    <script src="assets/js/jquery-2.1.1.js"></script>
    

    이 한 번만 globaly JQuery와 초기화합니다 -이 부트 스트랩에서 사용 모달 창에 대한 예를 들어 중요하다 ...


  9. 9.단계 1 : 명령을 사용 JQuery와 설치 NPM --save

    단계 1 : 명령을 사용 JQuery와 설치 NPM --save

    2 단계 : 당신은 단순히 각 가져올 수 있습니다 :

    'JQuery와'에서 $를 가져;

    그게 다야 .

    예제는 다음과 같습니다

    import { Component } from '@angular/core';
    import  $ from 'jquery';
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    
    export class AppComponent {
      title = 'app';
      constructor(){
        console.log($('body'));
      }
    
    
    }
    

  10. 10.각도 CLI를 사용하여

    각도 CLI를 사용하여

     npm install jquery --save
    

    스크립트 배열에서 angular.json에서

    "scripts": [ "node_modules/jquery/dist/jquery.min.js" ] // copy relative path of node_modules>jquery>dist>jquery.min.js to avoid path error
    

    이제 jQuery를 사용하여, 당신이 할 일은 그것으로 당신이 jQuery를 사용하여 원하는 구성 요소에서 다음 가져 오는 것입니다.

    예를 가져 오기 및 루트 구성 요소에 jQuery를 사용하기 위해

    import { Component, OnInit  } from '@angular/core';
    import * as $ from 'jquery'; // I faced issue in using jquery's popover
    Or
    declare var $: any; // declaring jquery in this way solved the problem
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
    
    
    ngOnInit() {
    }
    
    jQueryExampleModal() { // to show a modal with dummyId
       $('#dummyId').modal('show');
    }
    

  11. 11.// 설치 JQuery와 NPM 설치 JQuery와 --save

    // 설치 JQuery와 NPM 설치 JQuery와 --save

    // JQuery와 typings에 대한 유형 정의를 설치하는 설치 DT ~ JQuery와 --global --save

    //로 빌드 구성 파일에 jQuery 라이브러리를 추가 (파일 "각-CLI-build.js"에서) 지정

    vendorNpmFiles: [
      .........
      .........
      'jquery/dist/jquery.min.js'
    ]
    

    // 빌드 NG 빌드에서 jQuery 라이브러리를 추가하는 빌드를 실행

    // (시스템 config.js)에 상대 경로 설정 추가 / ** URL에 상대 경로를 매핑합니다. * / CONST지도 : 어떤 = { ....., ......., 'JQuery와': '업체 / JQuery와 / DIST' };

    /** User packages configuration. */
    const packages: any = {
    ......,
    'jquery':{ main: 'jquery.min',
    format: 'global',
    defaultExtension: 'js'}};
    

    // 구성 요소 파일에 jQuery 라이브러리를 가져

    import 'jquery';
    

    아래에있는 내 샘플 구성 요소의 코드는

    import { Component } from '@angular/core';
    import 'jquery';
    @Component({
      moduleId: module.id,
      selector: 'app-root',
      templateUrl: 'app.component.html',  
      styleUrls: ['app.component.css']
    })
    export class AppComponent {
      list:Array<number> = [90,98,56,90];
      title = 'app works!';
      isNumber:boolean = jQuery.isNumeric(89)  
      constructor(){}
    }
    

  12. 12.당신이 각-CLI를 사용하는 경우 당신은 할 수 있습니다 :

    당신이 각-CLI를 사용하는 경우 당신은 할 수 있습니다 :

    당신은 공식 각도 CLI 문서에 대한 자세한 내용을 찾을 수 있습니다


  13. 13.Angular2 IN에 사용 JQuery와 (4)

    Angular2 IN에 사용 JQuery와 (4)

    다음과 같이하세요

    JQuery와 및 JQuery와 유형 정의를 설치

    jQuery를 설치 NPM에 대한 설치 JQuery와 --save

    jQuery를 입력 해상력 설치 NPM를 들어 / JQuery와 --save-DEV 유형 @ 설치

    다음 단순히 jQuery를 가져

    import { Component } from '@angular/core';
    import * as $ from 'jquery';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent { 
      console.log($(window)); // jquery is accessible 
    }
    

  14. 14.내가 무지 렁이있어 이후, 나는 몇 가지 작업 코드가 좋을 거라 생각 했어요.

    내가 무지 렁이있어 이후, 나는 몇 가지 작업 코드가 좋을 거라 생각 했어요.

    상단 허용 대답은 나에게 깨끗하고 컴파일을주지 않도록 또한, 각-각도기의 Angular2 typings 버전은 jQuery를 $에 문제가 있습니다.

    여기에 내가 일하고있어하는 단계는 다음과 같습니다

    index.html을

    <head>
    ...
        <script   src="https://code.jquery.com/jquery-3.1.1.min.js"   integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
    ...
    </head>
    

    내부 my.component.ts

    import {
        Component,
        EventEmitter,
        Input,
        OnInit,
        Output,
        NgZone,
        AfterContentChecked,
        ElementRef,
        ViewChild
    } from "@angular/core";
    import {Router} from "@angular/router";
    
    declare var jQuery:any;
    
    @Component({
        moduleId: module.id,
        selector: 'mycomponent',
        templateUrl: 'my.component.html',
        styleUrls: ['../../scss/my.component.css'],
    })
    export class MyComponent implements OnInit, AfterContentChecked{
    ...
        scrollLeft() {
    
            jQuery('#myElement').animate({scrollLeft: 100}, 500);
    
        }
    }
    

  15. 15.그냥 써

    그냥 써

    declare var $:any;
    

    모든 수입 섹션 후에는 jQuery를 사용하고 index.html을 페이지에 jQuery 라이브러리를 포함 할 수 있습니다

    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    

    그것은 나를 위해 일한


  16. 16.성분 1)의 액세스에 DOM.

    성분 1)의 액세스에 DOM.

    import {BrowserDomAdapter } from '@angular/platform-browser/src/browser/browser_adapter';
    constructor(el: ElementRef,public zone:NgZone) {
         this.el = el.nativeElement;
         this.dom = new BrowserDomAdapter();
     }
     ngOnInit() {
       this.dom.setValue(this.el,"Adding some content from ngOnInit"); 
     }
    

    당신은 방법을 다음에 jQuery를 포함 할 수 있습니다. 2) 당신에게 angular2로드되기 전에 index.html을 jQuery에 파일을 포함

          <head>
        <title>Angular 2 QuickStart</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">
    
        <!-- jquery file -->
        <script src="js/jquery-2.0.3.min.js"></script>
        <script src="js/jquery-ui.js"></script>
        <script src="node_modules/es6-shim/es6-shim.min.js"></script>
        <script src="node_modules/zone.js/dist/zone.js"></script>
        <script src="node_modules/reflect-metadata/Reflect.js"></script>
        <script src="node_modules/systemjs/dist/system.src.js"></script>
        <script src="systemjs.config.js"></script>
        <script>
          System.import('app').catch(function(err){ console.error(err); });
        </script>
      </head>
    

    당신은 여기에 내가 JQuery와 UI 날짜 선택기를 사용하고, 다음과 같은 방법으로 jQuery를 사용할 수 있습니다.

        import { Directive, ElementRef} from '@angular/core';
        declare  var $:any;
        @Directive({
          selector: '[uiDatePicker]',
         })
        export class UiDatePickerDirective {
          private el: HTMLElement;
          constructor(el: ElementRef) {
            this.el = el.nativeElement;
    
         }
    
        ngOnInit() {
            $(this.el).datepicker({
             onSelect: function(dateText:string) {
                //do something on select
             }
            });
        }
    }
    

    나를 위해이 작품.


  17. 17.이 시점 전에 광산에 생성 된 모든 게시물에 언급되어 있기 때문에 나는 JQuery와의 설치를 생략하고있다. 그래서, 당신은 이미 jQuery를 설치했습니다. 이 같은 구성 요소로 t 가져 오기

    이 시점 전에 광산에 생성 된 모든 게시물에 언급되어 있기 때문에 나는 JQuery와의 설치를 생략하고있다. 그래서, 당신은 이미 jQuery를 설치했습니다. 이 같은 구성 요소로 t 가져 오기

    import * as $ from 'jquery';
    

    작동하지만 서비스를 생성하여이 작업을 수행 할 수있는 또 다른 '각도'방법이됩니다.

    스텝 없습니다. 1 : jquery.service.ts 파일을 만듭니다.

    // in Angular v2 it is OpaqueToken (I am on Angular v5)
    import { InjectionToken } from '@angular/core';
    export const JQUERY_TOKEN = new InjectionToken('jQuery');
    

    단계. 아니. 2 : app.module.ts에서 서비스를 등록

    import { JQUERY_TOKEN } from './services/jQuery.service';
    declare const jQuery: Object;
    
    providers: [
        { provide: JQUERY_TOKEN, useValue: jQuery },
    ]
    

    스텝 없습니다. 3 : 구성 요소 내-슈퍼 duper.component.ts에 서비스를 주사한다

    import { Component, Inject } from '@angular/core';
    
    export class MySuperDuperComponent {
        constructor(@Inject(JQUERY_TOKEN) private $: any) {}
    
        someEventHandler() {
            this.$('#my-element').css('display', 'none');
        }
    }
    

    누군가가 찬반 양론 두 방법의 설명 할 수 있다면 매우 감사하게 될 것입니다 : 서비스 대 가져 오기 등의 DI의 jQuery를 * 'JQuery와'에서 $로;


  18. 18.내가 찾은 것이 가장 효과적인 방법은 페이지 / 컴포넌트 생성자의 공 내부의 시간의 setTimeout을 사용하는 것입니다. 각도가 모든 하위 구성 요소를 완성 로딩 후이하자 다음 실행 사이클에서 jQuery를 실행합니다. 몇 가지 다른 구성 요소 방법을 사용할 수 있지만에서는 setTimeout 내에서 실행 할 때 모든 나는 일 최선을 노력했다.

    내가 찾은 것이 가장 효과적인 방법은 페이지 / 컴포넌트 생성자의 공 내부의 시간의 setTimeout을 사용하는 것입니다. 각도가 모든 하위 구성 요소를 완성 로딩 후이하자 다음 실행 사이클에서 jQuery를 실행합니다. 몇 가지 다른 구성 요소 방법을 사용할 수 있지만에서는 setTimeout 내에서 실행 할 때 모든 나는 일 최선을 노력했다.

    export class HomePage {
        constructor() {
            setTimeout(() => {
                // run jQuery stuff here
            }, 0);
        }
    }
    

  19. 19.여기에 나를 위해 일한 것입니다 - 웹팩 2 각도

    여기에 나를 위해 일한 것입니다 - 웹팩 2 각도

    나는 어떤 유형으로 $를 선언 시도하지만 난 어떤 JQuery와 모듈을 사용하려고 할 때마다 나는 $ (..) (예를 들어) 얻고 있었다. 날짜 선택기가 ()는 함수가 아닙니다

    내가 가지고 있기 때문에 jQuery를 내가 단순히 사용하여 내 구성 요소로 가져온 파일 내 vendor.ts에 포함

    'JQuery와'에서 $로 수입 *;

    지금은 (부트 스트랩-을 DateTimePicker 등)의 jQuery 플러그인을 사용할 수 있어요


  20. 20.또한 "InjectionToken"로 가져올을 시도 할 수 있습니다. 로 여기에 설명 : 사용 jQuery를 각도 / 타이프에서 타입 정의없이

    또한 "InjectionToken"로 가져올을 시도 할 수 있습니다. 로 여기에 설명 : 사용 jQuery를 각도 / 타이프에서 타입 정의없이

    당신은 단순히 jQuery를 글로벌 인스턴스를 주입하고 사용할 수 있습니다. 이를 위해 당신은 어떤 타입 정의 또는 typings을 필요로하지 않습니다.

    import { InjectionToken } from '@angular/core';
    
    export const JQ_TOKEN = new InjectionToken('jQuery');
    
    export function jQueryFactory() {
        return window['jQuery'];
    }
    
    export const JQUERY_PROVIDER = [
        { provide: JQ_TOKEN, useFactory: jQueryFactory },
    ];
    

    당신의 app.module.ts 올바르게 설정하는 경우 :

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { AppComponent } from './app.component';
    
    import { JQ_TOKEN } from './jQuery.service';
    
    declare let jQuery: Object;
    
    @NgModule({
        imports: [
            BrowserModule
        ],
        declarations: [
            AppComponent
        ],
        providers: [
            { provide: JQ_TOKEN, useValue: jQuery }
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    당신은 당신의 구성 요소를 사용할 수 있습니다 :

    import { Component, Inject } from '@angular/core';
    import { JQ_TOKEN } from './jQuery.service';
    
    @Component({
        selector: "selector",
        templateUrl: 'somefile.html'
    })
    export class SomeComponent {
        constructor( @Inject(JQ_TOKEN) private $: any) { }
    
        somefunction() {
            this.$('...').doSomething();
        }
    }
    

  21. 21.여기에 공식 문서로 글로벌 라이브러리 설치

    여기에 공식 문서로 글로벌 라이브러리 설치

    다시 서버는 당신이 그것을 실행하는 경우, 그것은 당신의 응용 프로그램 작업을해야합니다.

    당신은 'JQuery와'에서 단일 구성 요소 사용 가져 오기 $ 내부에 사용하려는 경우; 구성 요소 내부


  22. 22.다른 사람은 이미 게시. 하지만 난 그래서 몇 가지 새로운 올 사람을 도울 수 있습니다 여기에 간단한 예제를 제공합니다.

    다른 사람은 이미 게시. 하지만 난 그래서 몇 가지 새로운 올 사람을 도울 수 있습니다 여기에 간단한 예제를 제공합니다.

    스텝 1 : index.html을 파일 참조 JQuery와 CDN에서

         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    

    스텝 2 : 우리가 버튼의 클릭에 DIV 또는 숨기기 DIV를 보여주고 싶은 가정 :

     <input type="button" value="Add New" (click)="ShowForm();">
    
    
     <div class="container">
      //-----.HideMe{display:none;} is a css class----//
    
      <div id="PriceForm" class="HideMe">
         <app-pricedetails></app-pricedetails>
      </div>
      <app-pricemng></app-pricemng>
     </div>
    

    스텝 3 : 울부 짖는 소리로 가져 오기 선언 $ 울부 짖는 구성 요소 파일에서 :

    declare var $: any;
    

    보다 것은 울부 짖는 소리와 같은 함수를 만들 :

     ShowForm(){
       $('#PriceForm').removeClass('HideMe');
     }
    

    그것은 최근의 각도와 JQuery와 함께 작동합니다


  23. 23.다음과 같이 첫째, jQuery를 사용하여 NPM를 설치합니다 :

    다음과 같이 첫째, jQuery를 사용하여 NPM를 설치합니다 :

    npm install jquery — save
    

    다음과 같이 [] 속성을, 그리고 jQuery를에 대한 경로를 포함 : 둘째, 당신의 각도 CLI 프로젝트 폴더의 루트에 ./angular-cli.json 파일로 이동하여 스크립트를 찾을 수 있습니다 :

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

    이제, jQuery를 사용하여, 당신이 할 일은 당신이 jQuery를 사용하여 원하는 구성 요소를 가져 오는 것입니다.

    import * as $ from 'jquery';
    (or)
    declare var $: any;
    

    특히 두 번째 줄에, 클릭에 애니메이션 사업부에 jQuery를 사용하는 다음 코드를 살펴 보자. 우리는 jQuery를에서 $로 모든 것을 가져.

    import { Component, OnInit  } from '@angular/core';
    import * as $ from 'jquery';
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      title = 'Look jQuery Animation working in action!';
    
      public ngOnInit()
      {
        $(document).ready(function(){
            $("button").click(function(){
                var div = $("div");  
                div.animate({left: '100px'}, "slow");
                div.animate({fontSize: '5em'}, "slow");
            });
        });
      }
    }
    

  24. 24.JQuery와 설치

    JQuery와 설치

    터미널 $의 NPM jQuery를 설치

    (부트 스트랩 4 ...)

    popper.js를 설치 NPM 터미널 $

    터미널 $의 NPM 부트 스트랩을 설치

    그런 다음 app.module.ts에 import 문을 추가합니다.

    import 'jquery'
    

    (부트 스트랩 4 ...)

    import 'popper.js'
    import 'bootstrap'
    

    이제 더 이상 자바 스크립트를 참조하는