【问题标题】:Using JQuery Plugins in Angular 4 Applications在 Angular 4 应用程序中使用 JQuery 插件
【发布时间】:2017-06-26 03:22:22
【问题描述】:

所以我目前正在尝试在我的 Angular 4 应用程序中使用一些 jquery 插件,如 Magnific-Popup 等,但我遇到了一些麻烦。我通过在终端中执行 npm install --save-dev @types/jquery 安装了 jquery,并且效果很好,但是我无法让实际的插件正常工作。这是我最初尝试的,

 @Component({
 selector: 'app-showcase',
 templateUrl: './showcase.component.html',
 styleUrls: ['./showcase.component.css']
 })
 export class ShowcaseComponent implements OnInit {
 @ViewChild("elementRef") elref2: ElementRef;

 constructor(private elRef: ElementRef) { }

 ngOnInit() {


  jQuery(this.elref2.nativeElement).magnificPopup();

  }

 ngAfterViewInit() {

  }

为了让 typescript 识别 magnificPopup() 函数,我尝试将 magnificPopup 文档中的脚本导入我的 index.html(在 body 标签的底部),但据我所知,这不是在职的。 Webstorm 说“无法解析文件 jquery.magnific-popup.js”。我也在加载 jquery.min 脚本,这似乎工作正常。

我也尝试运行 npm-install magnific-popup,但也失败了。此外,我尝试将脚本添加到 angular.JSON 文件中,但无济于事。

我想我要问的是,什么是以及如何在我的 angular 4 应用程序中安装和使用第三方 jquery 插件(如 magnific-pop up)?

谢谢,感谢任何帮助。

【问题讨论】:

    标签: javascript jquery angular typescript plugins


    【解决方案1】:

    我有一个 Angular 项目,我需要(目前)使用一个依赖于 jquery 的插件(nanoscroller)。我使用 angular-cli 完成所有构建过程,并且我的 angular-cli.json 文件在“脚本”属性下具有以下内容:

     "scripts": [
            "../node_modules/jquery/dist/jquery.js",
            "../node_modules/nanoscroller/bin/javascripts/jquery.nanoscroller.js"
          ]

    然后我使用插件如下:

    import { AfterViewInit, Component, ElementRef, OnDestroy, Renderer, ViewChild } from "@angular/core";
    
    declare var jQuery: any;
    
    @Component({
        selector: "app-root",
        templateUrl: "./app.component.html",
        styleUrls: ["./app.component.scss"]
    })
    export class AppComponent implements AfterViewInit {
        layoutMenuScroller: HTMLDivElement;
        @ViewChild("layoutMenuScroller") layoutMenuScrollerViewChild: ElementRef;
    
        constructor() {
    
        }
    
        ngAfterViewInit() {
             this.layoutMenuScroller = <HTMLDivElement>this.layoutMenuScrollerViewChild.nativeElement;
            jQuery(this.layoutMenuScroller).nanoScroller({ flash: true });
    
        }
        //  etc..
    }

    也许您可以将此应用于您的用例。

    【讨论】:

    • 我尝试在您的示例中使用 nanoscroller 插件执行此操作,但出现此错误:“JQuery”类型上不存在属性“nanoScroller”。
    • @ay123123 你正在使用 angular-cli?
    • 我很难过。这个设置对我有用。不确定您的代码中发生了什么错误。
    • 实际上,您的设置成功了!我只是在 angular.json 文件中错误地加载了脚本。谢谢!
    • 很高兴听到这个消息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多