如何在Angular2中使用jQuery插件

How can I use a jQuery plugin in Angular2?

本文关键字:jQuery 插件 Angular2      更新时间:2023-09-26

我正试图在我的Angular2项目中使用packery。然而,我似乎无法让它在指令中发挥作用。这是我的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
    });
  }
}

虽然当我在没有选项的情况下使用它时,它会初始化,但代码不起作用。即

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

然而,有了这些选项,我会得到一个错误

Supplied parameters do not match any signature of call target.

打字员文件已将类型声明为可选类型。

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

如果有人能引导我正确实现TypeScript中的jQuery插件,我将不胜感激。谢谢

我终于使用发布在https://stackoverflow.com/a/34570534/6070591

我当前的指令代码

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
    });
  }
}

您可能需要导入它或检查版本兼容性:

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

Angular是否使用jQuery库

是的,Angular可以在应用程序启动时使用jQuery。如果您的脚本路径中没有jQuery,Angular将返回到它自己的jQuery子集实现,我们称之为jQLite。

Angular 1.3仅支持jQuery 2.1或更高版本。jQuery1.7和更新版本可能可以正确地与Angular配合使用,但我们不能保证这一点。