Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

typescript - How to use jQuery with javascript in angular 2

    import {Component, ElementRef, OnInit} from 'angular2/core';
    declare var jQuery:any;
    @Component({
      selector: 'jquery-integration',
      templateUrl: './components/jquery-integration/jquery-integration.html'
    })
    export class JqueryIntegration implements OnInit {
      elementRef: ElementRef;
      constructor(elementRef: ElementRef) {
        this.elementRef = elementRef;
      }
      ngOnInit() {
        jQuery(this.elementRef.nativeElement).draggable({
        containment:'#draggable-parent'
      });
    }
  }

Can jQuery be used with TypeScript in Angular2 like the above? How do I use jQuery with JavaScript in Angular2?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...