简体   繁体   English

如何在Angular2中使用jQuery插件?

[英]How can I use a jQuery plugin in Angular2?

I'm trying to use packery in one of my Angular2 projects. 我正在尝试在我的Angular2项目之一中使用包装。 However I just can't seem to get it to work in a directive. 但是我似乎无法使其在指令中工作。 This is my packery.directive.ts file 这是我的packery.directive.ts文件

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

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[packery]'
})

export class Packery {

  constructor(el: ElementRef) {
    jQuery(el.nativeElement).packery({
      itemSelector: '.grid-item',
      gutter: 10
    });
  }
}

The code doesn't work although it initializes when I use it without the options. 尽管我在没有选项的情况下将其初始化,但该代码无法正常工作。 ie

.....
export class Packery {

  constructor(el: ElementRef) {
    jQuery(el.nativeElement).packery();
  }
}

However, with the options, I'll get an error 但是,使用这些选项,我会得到一个错误

Supplied parameters do not match any signature of call target.

The typings file already has the types declared as optional. 类型文件已经具有声明为可选的类型。

declare module "packery" {
interface PackeryOptions {
    itemSelector?: string;
    gutter?: number;
......................

Appreciate it if someone can lead me to the direction of correctly implementing a jQuery plugin in TypeScript. 如果有人可以引导我转向在TypeScript中正确实现jQuery插件的方向,我们将不胜感激。 Thanks. 谢谢。

I've finally managed to solved it using the solution posted at https://stackoverflow.com/a/34570534/6070591 我终于设法使用https://stackoverflow.com/a/34570534/6070591上发布的解决方案解决了它

My current directive code 我当前的指令代码

import { Directive, ElementRef, Inject, OnInit } from '@angular/core';

declare var jQuery: any;

@Directive({
  selector: '[packery]'
})

export class Packery implements OnInit {
  elementRef: ElementRef;

  constructor( @Inject(ElementRef) elementRef: ElementRef) {
    this.elementRef = elementRef;
  }


  ngOnInit() {
    jQuery(this.elementRef.nativeElement).packery({
      // options
      itemSelector: '.grid-item',
      gutter: 10
    });
  }

}

You probably need to import it or check version compatibility: 您可能需要导入它或检查版本兼容性:

From the FAQ: https://docs.angularjs.org/misc/faq 从常见问题解答中: https//docs.angularjs.org/misc/faq

Does Angular use the jQuery library? Angular是否使用jQuery库?

Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped. 是的,如果在引导应用程序时Angular出现在您的应用程序中,则可以使用jQuery。 If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite. 如果您的脚本路径中不存在jQuery,则Angular会退回到它自己的jQuery子集(我们称为jQLite)的实现。

Angular 1.3 only supports jQuery 2.1 or above. Angular 1.3仅支持jQuery 2.1或更高版本。 jQuery 1.7 and newer might work correctly with Angular but we don't guarantee that. jQuery 1.7和更高版本可能可以与Angular一起正常使用,但我们不保证一定如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM