How to use jQuery with javascript in angular 2

前端 未结 7 812
说谎
说谎 2020-12-05 01:13
    import {Component, ElementRef, OnInit} from \'angular2/core\';
    declare var jQuery:any;
    @Component({
      selector: \'jquery-integration\',
      templat         


        
相关标签:
7条回答
  • 2020-12-05 01:54

    we can use like as follow:

    var jq=require('./jquery.min.js');
    .....
    export class AppComponent{
      ngOnInit(){
       jq();
       console.log($('body'))  // show:[body, prevObject: r.fn.init[1]]
                               //ok!normal operation!
      }
    }
    
    0 讨论(0)
  • 2020-12-05 02:01

    Once you have the JQuery typescript library installed, reference it in this way

    ///<reference path="../typings/jquery/jquery.d.ts" />
    

    Then make the necessary imports

    import {Component, AfterViewInit} from 'angular2/core';
    

    Now write the class

    @Component({
      selector: 'my-app',
      templateUrl: 'app/html/app.component.html'
    })
    
    export class AppComponent implements AfterViewInit {
      ngAfterViewInit() {
        // Your jQuery code goes here
        $('#here').text("HALLO! ^_^");
      }
    }
    
    0 讨论(0)
  • 2020-12-05 02:01

    You should not tie Angular component with jQuery at any price

    1. Load jQuery with <script> tag.
    2. Add jQuery document ready handler.
    
      $('document').ready((function($) {
    
          return function() {
    
            // DOM is ready and $ is a reference to jQuery
    
            // It's time to things done using $
    
          };
    
      })(jQuery));
    
    

    Pros:

    • Angular component is free from jQuery dependency.
    • Easier to test such a component, maintain and re-use.
    • jQuery code is isolated.

    However, if you need to use the jQuery inside the components use services or directives.

    If you have a problems with loading a partial views use jQuery event handler on document node and jQuery window load handler.

    0 讨论(0)
  • 2020-12-05 02:03

    In my opinion: if you do it right and if you keep it minimal, you should go with that.

    1. Install jQuery Typings in project: tsd install jQuery
    2. Load jQuery with script tag ( or other loaders... )
    3. Wrap any jQuery plugin with Angular 2 Directive

    Example:

    @Directive({
      selector: "[sm-dropdown]"
    })
    export class SMDropdown {
      constructor(el: ElementRef) {
        jQuery(el.nativeElement).dropdown();
      }
    }
    

    Consider this Plunker:

    https://plnkr.co/edit/MMNWGh?p=preview

    Don't:

    • Don't use it for DOM manipulation, there is Angular way...
    • Don't use it for AJAX calls, there is Angular way...
    • Don't use it for animation, ngAnimation is coming...
    0 讨论(0)
  • 2020-12-05 02:08

    You must tell where you can find your jQuery typeScript definition. This can be done in a typings.d.ts file where you put your typings like this :

    ///<reference path="../typings/jquery/jquery.d.ts" />
    

    Or you can install typings via node and let your configuration load it automatically. This is what angular-cli do.

    After that, to use jQuery with Angular2 you must understand a fondamental mechanism. Angular2 has it's own dom representation and jQuery manipulates this dom. That's why people say's "Don't use jQuery with Angular2". It's not right. Angular2 come with a solution for this problem. It calls it ControlValueAccessor. The goal of this, is to alert angular when your jQuery plugin modifies the DOM and also let angular notify your plugin when it modify the DOM too.

    Let me explain this through an example of date picker calendar.

    import { Directive, ElementRef, OnInit, AfterViewInit, Input, forwardRef, OnDestroy } from '@angular/core';
    import { Moment } from 'moment';
    import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
    
    
    const DATE_PICKER_VALUE_ACCESSOR = {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => FnCalendarDirective),
      multi: true,
    
    };
    
    @Directive({
      selector: '[fn-calendar]',
      providers: [DATE_PICKER_VALUE_ACCESSOR],
    })
    export class FnCalendarDirective implements OnInit, AfterViewInit, ControlValueAccessor, OnDestroy {
    
    
      @Input() format: string = 'DD/MM/YYYY HH:mm';
      @Input() showClose: boolean = true;
      @Input() sideBySide: boolean = false;
      @Input() ngModel;
    
      private onTouched = () => { };
      private onChange: (value: string) => void = () => { };
    
      constructor(private el: ElementRef) {
      }
    
      ngOnInit() {
    
      }
    
      ngAfterViewInit() {
        $(this.el.nativeElement).datetimepicker({
          locale: 'fr',
          sideBySide: this.sideBySide,
          format: this.format,
          showClose: this.showClose,
          icons: {
            time: 'fa fa-clock-o',
            date: 'fa fa-calendar',
            up: 'fa fa-chevron-up',
            down: 'fa fa-chevron-down',
            previous: 'fa fa-chevron-left',
            next: 'fa fa-chevron-right',
            today: 'fa fa-bullseye',
            clear: 'fa fa-trash',
            close: 'fa fa-times'
          },
        }).on('dp.change', event => {
          let date: Moment = (<Moment>(<any>event).date);
          if (date) {
            let value = date.format(this.format);
            this.onChange(value);
          }
        });
        this.writeValue(this.ngModel);
      }
    
      writeValue(date: string) {
        $(this.el.nativeElement).datetimepicker().data('DateTimePicker').date(date);
      }
    
      registerOnChange(fn: any) {
        this.onChange = fn;
      }
    
      registerOnTouched(fn: any) {
        this.onTouched = fn;
      }
    
      ngOnDestroy() {
        $(this.el.nativeElement).datetimepicker().data('DateTimePicker').destroy();
      }
    }
    

    Important things here, are writeValue method that let Angular2 notify your jquery plugin that a change is producing. And registerOnChange, that let you notify Angular2 that your plugin make a change to the DOM.

    In conclusion, the key to use jQuery, is to wrap your jQuery plugin inside directive and to implement a CustomValueAccesor to handle communication between your plugin and Angular2.

    To find typings, you can use DefinitlyTyped GitHub which is a repository of typings definition from lot of js library.

      [1]: http://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html
    
    0 讨论(0)
  • 2020-12-05 02:09

    Quickest and dirtiest way to do it:

    (<any>window).$('.alert')
    
    0 讨论(0)
提交回复
热议问题