How to import jQuery to Angular2 TypeScript projects?

前端 未结 7 1852
一向
一向 2020-12-01 14:48

I want to wrap some jQuery code in an Angular2 directive.

I installed jQuery library for Typings into my project with the following command:

typings in

相关标签:
7条回答
  • 2020-12-01 15:07

    This is old question and there're some answers already. However existing answers are overly complicated ( answer from user1089766 contains many unnecessary stuffs). Hope this helps someone new.

    Add <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script> Into your index.html file.

    Create jQuery.Service.ts:

    import {InjectionToken} from "@angular/core";
    export let jQueryToken = new InjectionToken('jQuery'); 
    

    In you module file, add this jQueryToken to provider:

    providers:[
    {
        provide: jQueryToken,
        useValue: jQuery
    
    }] 
    

    Now @Inject(jQueryToken) and it is ready to use. Let say you want to use inside a component name ExperimentComponent then:

    import {Component, Inject, OnInit} from '@angular/core';
    import {jQueryToken} from "./common/jquery.service";
    
    @Component({
        selector: 'app-experiment',
        templateUrl: './experiment.component.html',
        styleUrls: ['./experiment.component.css']
    })
    export class ExperimentComponent implements OnInit {
    
        constructor(@Inject(jQueryToken) private $: any) {
            $(document).ready(function () {
                alert(' jQuery is working');
            });
        }
    
        ngOnInit() {
        }
    
    }
    

    Whenever you open ExperimentComponent the alert function will call and pop up the message.

    0 讨论(0)
  • 2020-12-01 15:08

    jQuery.service.ts

     import { OpaqueToken } from '@angular/core'
    export let JQ_TOKEN = new OpaqueToken('jQuery');
    

    index.ts`

    export * from './jQuery.service';
    

    app.module.ts

    declare let jQuery : Object;

    @NgModule({
      providers: [
        { provide: TOASTR_TOKEN, useValue: toastr },
        { provide: JQ_TOKEN, useValue: jQuery },
    })
    export class AppModule { }
    

    how to use Jquery in component

       import { Component, Input, ViewChild, ElementRef, Inject } from '@angular/core'
    import { JQ_TOKEN } from './jQuery.service'
    
    @Component({
      selector: 'simple-modal',
      template: `
      <div id="{{elementId}}" #modalcontainer class="modal fade" tabindex="-1">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
              <h4 class="modal-title">{{title}}</h4>
            </div>
            <div class="modal-body" (click)="closeModal()">
              <ng-content></ng-content>
            </div>
          </div>
        </div>
      </div>
      `,
      styles: [`
        .modal-body { height: 250px; overflow-y: scroll; }
      `]
    })
    export class SimpleModalComponent {
      @Input() title: string;
      @Input() elementId: string;
      @Input() closeOnBodyClick: string;
      @ViewChild('modalcontainer') containerEl: ElementRef;
    
      constructor(@Inject(JQ_TOKEN) private $: any) {}
    
      closeModal() {
        if(this.closeOnBodyClick.toLocaleLowerCase() === "true") {
          this.$(this.containerEl.nativeElement).modal('hide');
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-01 15:13

    You could also load your jQuery Javascript file in a normal script tag in the head section of your index.html.

    <html>
        <head>
            <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" />
            <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.js" />
    
            ...
        </head>
        ...
    

    Then in the component or directive where you need it, just declare the $ variable needed for jQuery, since you won't have the typings for all the plugins you need:

    import {Directive} from '@angular/core';
    
    declare var $: any;
    
    @Directive({
        selector: "my-first-directive"
    })
    
    export class MyFirstDirective {
        constructor() {
            $(document).ready(function () {
                alert("Hello World");
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-01 15:15

    If you are using "@angular/cli" then install:

    npm install jquery --save
    

    Second step install:

    install: npm install @types/jquery --save-dev
    

    And find your file name in "angular-cli.json" on the root and add the inside of as like:

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

    Now it will work.

    0 讨论(0)
  • 2020-12-01 15:18

    I don't think it should be a issue to use jquery with angular 2. If the typings and the dependencies for jquery are installed properly, then it should not be a issue to use jquery in angular 2.

    I was able to use jquery in my angular 2 project with proper installation. And by proper installation, I mean the installation of jquery typings in order to recognize it in typescript.

    After that, I was able to use jquery in following way:

    jQuery(document).ready({
        ()=>{
            alert("Hello!");
        };
    });
    
    0 讨论(0)
  • 2020-12-01 15:21

    Step 1: get jquery in your project

    npm install jquery
    

    Step 2: add type for jquery

    npm install -D @types/jquery
    

    Step 3: Use it in your component!

    import * as $ from 'jquery';
    

    Ready to use $!

    0 讨论(0)
提交回复
热议问题