Programing

Angular 4에서 jQuery 플러그인을 사용하는 방법은 무엇입니까?

lottogame 2020. 9. 22. 20:57
반응형

Angular 4에서 jQuery 플러그인을 사용하는 방법은 무엇입니까?


각도 프로젝트에서 범위 슬라이더를 사용하고 싶은데 각도 4에 사용 가능한 모듈 하나를 사용해 보았습니다.

컴파일하는 동안 잘 작동하지만 배포를 위해 빌드하려고하면 아래 오류가 발생합니다.

여기에 이미지 설명 입력

Angular 프로젝트에서 직접 jQuery 플러그인을 사용하는 옵션을 확인했고 Angular 2에서만 옵션을 얻었습니다.

Angular 4에서 jQuery 플러그인을 사용할 수있는 방법이 있습니까?

알려주세요.

미리 감사드립니다!


예, Angular 4와 함께 jquery를 사용할 수 있습니다.

단계 :

1) index.html태그의 줄 아래에 넣습니다.

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

2) 아래의 컴포넌트 ts 파일에서 다음과 같이 var를 선언해야합니다.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular 4 with jquery';
  toggleTitle(){
    $('.title').slideToggle(); //
  }

}

다음과 같은 해당 html 파일에이 코드를 사용합니다.

<h1 class="title" style="display:none">
  {{title}}
</h1>
<button (click)="toggleTitle()"> clickhere</button>

이것은 당신을 위해 작동합니다. 감사


npm으로 jquery 설치

npm install jquery --save

입력 추가

npm install --save-dev @types/jquery

angular-cli.json에 스크립트 추가

"apps": [{
  ...
  "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
  ],
  ...
}]

프로젝트 구축 및 제공

ng build

도움이 되었기를 바랍니다! 코딩 즐기기


Install jQuery using NPM Jquery NPM

npm install jquery

Install the jQuery declaration file

npm install -D @types/jquery

Import jQuery inside .ts

import * as $ from 'jquery';

call inside class

export class JqueryComponent implements OnInit {

constructor() {
}

ngOnInit() {
    $(window).click(function () {
        alert('ok');
        });
    }

}

You are not required to declare any jQuery variable as you installed @types/jquery.

declare var jquery:any;   // not required
declare var $ :any;   // not required

You should have access to jQuery everywhere.

The following should work:

jQuery('.title').slideToggle();

You should not use jQuery in Angular. While it is possible (see other answers for this question), it is discouraged. Why?

Angular holds an own representation of the DOM in its memory and doesn't use query-selectors (functions like document.getElementById(id)) like jQuery. Instead all the DOM-manipulation is done by Renderer2 (and Angular-directives like *ngFor and *ngIf accessing that Renderer2 in the background/framework-code). If you manipulate DOM with jQuery yourself you will sooner or later...

  1. Run into synchronization problems and have things wrongly appearing or not disappearing at the right time from your screen
  2. Have performance issues in more complex components, as Angular's internal DOM-representation is bound to zone.js and its change detection-mechanism - so updating the DOM manually will always block the thread your app is running on.
  3. Have other confusing errors you don't know the origin of.
  4. Not being able to test the application correctly (Jasmine requires you to know when elements have been rendered)
  5. Not being able to use Angular Universal or WebWorkers

If you really want to include jQuery (for duck-taping some prototype that you will 100% definitively throw away), I recommend to at least include it in your package.json with npm install --save jquery instead of getting it from google's CDN.

TLDR: For learning how to manipulate the DOM in the Angular way please go through the official tour-of heroes tutorial first: https://angular.io/tutorial/toh-pt2 If you need to access elements higher up in the DOM hierarchy (parent or document body) or for some other reason directives like *ngIf, *ngFor, custom directives, pipes and other angular utilities like [style.background], [class.myOwnCustomClass] don't satisfy your needs, use Renderer2: https://www.concretepage.com/angular-2/angular-4-renderer2-example


Try this:

import * as $ from 'jquery/dist/jquery.min.js';

Or add scripts to angular-cli.json:

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

and in your .ts file:

declare var $: any;

You can update your jquery typings version like so

npm install --save @types/jquery@latest

I had this same error and I've been at if for 5 days surfing the net for a solution.it worked for me and it should work for you


다른 라이브러리를 프로젝트에서 사용할 필요가있는 경우 --typescript-- 프로젝트뿐만 아니라-angle-메서드, 유형, 함수 등의 정보가 포함 된 tds (TypeScript 선언 파일)를 찾을 수 있습니다., 일반적으로 가져올 필요없이 TypeScript에서 사용할 수 있습니다. var가 마지막 자원임을 선언하십시오.

npm install @types/lib-name --save-dev

웹팩을 사용하여 제공수 있습니다 . 그러면 DOM이 자동으로 주입됩니다.

module.exports = {
  context: process.cwd(),
  entry: {
    something: [
      path.join(root, 'src/something.ts')
    ],
    vendor: ['jquery']
  },
  devtool: 'source-map',
  output: {
    path: path.join(root, '/dist/js'),
    sourceMapFilename: "[name].js.map",
    filename: '[name].js'
  },
  module: {
    rules: [
      {test: /\.ts$/, exclude: /node_modules/, loader: 'ts-loader'}
    ]
  },
  resolve: {
    extensions: ['.ts', '.es6', '.js', '.json']
  },
  plugins: [

    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    }),

  ]
};

사용해보십시오-선언 let $ : any;

또는 'jquery / dist / jquery.min.js'에서 *를 $로 가져옵니다. lib의 정확한 경로 제공


ngOnInit() {
     const $ = window["$"];
     $('.flexslider').flexslider({
        animation: 'slide',
        start: function (slider) {
          $('body').removeClass('loading')
        }
     })
}

참고 URL : https://stackoverflow.com/questions/43934727/how-to-use-jquery-plugin-with-angular-4

반응형