如何在角度2中使用jQuery和javascript

Bud*_*aka 15 jquery typescript angular

    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'
      });
    }
  }
Run Code Online (Sandbox Code Playgroud)

可以像上面那样在Angular2中使用jQuery与jQuery一起使用吗?如何在Angular2中使用jQuery和JavaScript?

Vla*_*vic 21

在我看来:如果你做得对,如果你把它保持在最低限度,你就应该坚持下去.

  1. 在项目中安装jQuery Typings:tsd install jQuery
  2. 使用脚本标记(或其他加载器...)加载jQuery
  3. 使用Angular 2 Directive包装任何jQuery插件

例:

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

考虑一下这个Plunker:

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

别:

  • 不要将它用于DOM操作,有Angular方式......
  • 不要用它来进行AJAX调用,有Angular方式......
  • 不要用它来制作动画,ngAnimation即将到来......


Sau*_*abh 7

一旦安装了JQuery typescript库,就以这种方式引用它

///<reference path="../typings/jquery/jquery.d.ts" />
Run Code Online (Sandbox Code Playgroud)

然后进行必要的进口

import {Component, AfterViewInit} from 'angular2/core';
Run Code Online (Sandbox Code Playgroud)

现在写课

@Component({
  selector: 'my-app',
  templateUrl: 'app/html/app.component.html'
})

export class AppComponent implements AfterViewInit {
  ngAfterViewInit() {
    // Your jQuery code goes here
    $('#here').text("HALLO! ^_^");
  }
}
Run Code Online (Sandbox Code Playgroud)


Duy*_*ran 7

我该怎么做才能解决这个问题:

对于库不支持@types/和库需要加载文件时加载(平均库需要在文件的脚本标签中添加)

  1. npm install jquery --save
  2. 添加JS/CSS文件scriptsstylesangular-cli.json

    "scripts": ["../node_modules/path to file", "./assets/path to file"]

对于支持的库@types/,只需运行即可npm install @types/jquery --save-dev

要使用该库,请declare var jQuery: any;在注释之前添加@Directive@Component想要使用lib

P/S:我用angular-cliwebpack在我的项目,有可能不同systemjs