如何在 angular 2 中使用 jQuery 和 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35054004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:01:30  来源:igfitidea点击:

How to use jQuery with javascript in angular 2

jquerytypescriptangular

提问by Buddhika Kulathilaka

    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?

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

回答by Vlado Tesanovic

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
  1. 在项目中安装 jQuery Typings:tsd install jQuery
  2. 使用脚本标记加载 jQuery(或其他加载器...)
  3. 使用 Angular 2 指令包装任何 jQuery 插件

Example:

例子:

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

Consider this Plunker:

考虑这个Plunker:

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

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...
  • 不要将它用于 DOM 操作,有 Angular 方式...
  • 不要将它用于 AJAX 调用,有 Angular 方式...
  • 不要用它做动画,ngAnimation 来了……

回答by Saurabh

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

安装 JQuery 打字稿库后,以这种方式引用它

///<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! ^_^");
  }
}

回答by Duy Tran

What I do to solve this issue:

我如何解决这个问题:

For library doesn't support @types/and library need to load when document loaded (mean libraries need to add in script tag of document)

对于库不支持@types/并且库需要在文档加载时加载(意味着库需要添加到文档的脚本标签中)

  1. Run npm install jquery --save
  2. Add js/css files in scriptsor stylesof angular-cli.jsonlike

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

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

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

For library supported @types/, just run npm install @types/jquery --save-dev

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

To use the library, add declare var jQuery: any;before annotation @Directiveor @Componentwant to use the lib

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

P/S: I use angular-cliwith webpackin my project, maybe different with systemjs

P/S:我在我的项目中使用angular-cliwith webpack,可能与 with 不同systemjs

回答by Scandinave

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 :

你必须告诉你在哪里可以找到你的 jQuery typeScript 定义。这可以在 Typings.d.ts 文件中完成,您可以在其中放置您的类型,如下所示:

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

或者您可以通过节点安装类型并让您的配置自动加载它。这就是 angular-cli 所做的。

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.

之后,要在 Angular2 中使用 jQuery,您必须了解基本机制。Angular2 有它自己的 dom 表示,jQuery 操作这个 dom。这就是为什么人们说“不要在 Angular2 中使用 jQuery”。这是不对的。Angular2 为这个问题提供了解决方案。它称之为ControlValueAccessor。这样做的目的是在您的 jQuery 插件修改 DOM 时提醒 angular,并在它也修改 DOM 时让 angular 通知您的插件。

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.

这里重要的是 writeValue 方法,它让 Angular2 通知您的 jquery 插件正在产生更改。和 registerOnChange,它让你通知 Angular2 你的插件对 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.

总之,使用 jQuery 的关键是将您的 jQuery 插件包装在指令中并实现一个 CustomValueAccesor 来处理您的插件和 Angular2 之间的通信。

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

要查找类型,您可以使用DefinitlyTypedGitHub,它是来自许多 js 库的类型定义的存储库。

  [1]: http://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

回答by John Smith

You should not tie Angular component with jQuery at any price

你不应该以任何代价将 Angular 组件与 jQuery 联系起来

  1. Load jQuery with <script>tag.
  2. Add jQuery document ready handler.
  1. 加载带有<script>标签的jQuery 。
  2. 添加 jQuery 文档就绪处理程序。
  $('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.
  • Angular 组件不受 jQuery 依赖。
  • 这样的组件更容易测试、维护和重用。
  • jQuery 代码是隔离的。

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.

但是,如果您需要在组件内部使用 jQuery,请使用服务或指令。

如果您在加载部分视图时遇到问题,请在文档节点和 jQuery 窗口加载处理程序上使用 jQuery 事件处理程序。

回答by u7281846

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!
  }
}