【问题标题】:How to properly use JQuery and Bootstrap in latest Angular versions如何在最新的 Angular 版本中正确使用 JQuery 和 Bootstrap
【发布时间】:2018-05-18 22:59:15
【问题描述】:

是的,这个问题可能会重复。但我只是不让这个设置以任何方式工作。

我几乎什么都试过了:

  • 通过 CDN 将库直接放入 index.html。
  • 通过 NPM 安装它们,然后将它们添加到 angular-cli.json 脚本字段。
  • 将模块直接导入到我的组件中,使用别名 JQuery(import * as $ from 'jquery')和普通导入(import 'jquery')。

我尝试了其他设置,例如在根组件中进行导入,在不同位置导入这些库...但我无法正常工作。

目前,我需要使用一个 Bootstrap 模式和一个也适用于 JQuery 的 Datepicker 组件,但这对我来说是不可能的。有时我得到“$ 未定义”,有时我得到其他错误。

那么现在,我要问了:在最新的 Angular 版本中,对于这个问题的真正解决方案是什么?我应该如何进行导入?

谢谢!

编辑:当前情况:

  • 将依赖项添加到 angular-cli.json 文件中:

    “样式”:[ “样式.css”, “../node_modules/bootstrap/dist/css/bootstrap.min.css”, “../node_modules/font-awesome/css/font-awesome.css” ], “脚本”:[ "../node_modules/jquery/dist/jquery.min.js", “../node_modules/bootstrap/dist/js/bootstrap.bundle.min.js” ],

    • 我尝试调用 bootstrap 必须添加到 Jquery 的 .modal() 函数:

    ( $('#myModal')).modal({ 背景:真实, 重点:真实, 显示:真 })

但它只是抛出......:

SegmentsComponent.html:15 ERROR ReferenceError: $ is not defined
    at SegmentsComponent.openModal (segments.component.ts:55)
    at Object.eval [as handleEvent] (SegmentsComponent.html:15)
    at handleEvent (core.js:13255)
    at callWithDebugContext (core.js:14740)
    at Object.debugHandleEvent [as handleEvent] (core.js:14327)
    at dispatchEvent (core.js:9704)
    at eval (core.js:10318)
    at HTMLAnchorElement.eval (platform-browser.js:2614)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4620)

有什么帮助吗?

【问题讨论】:

    标签: javascript jquery twitter-bootstrap angular


    【解决方案1】:

    mmmmm .. 看起来很奇怪.. 它可以给你 $ 的唯一原因没有定义is because you DON'T INCLUDE IT well..

    所以我可以向你建议的是DOUBLE check your jquery pathscripts :[] section ..

    记住 ..the path is intended from the src(或您的根:条目)folder

    还检查 jquery 版本.. 我看到 NPM don't include jquery when you do install bootstrap ... 所以手动安装 jquery 并获取正确的版本..

    AND 在您的 .ts 文件中 .. 您的 ts 文件头部有 declare var $ : any 吗? ...

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      您需要使用包管理器或 CDN 安装 Jquery 和 bootstrap(Bopper for Bootstrap 4)。您的 .angular-cli.json 文件必须如下所示:

      "scripts": [
          "../node_modules/jquery/dist/jquery.js",
          "../node_modules/popper.js/dist/umd/popper.js",
          "../node_modules/bootstrap/dist/js/bootstrap.js"
      ],
      

      确保这三个文件存在。

      【讨论】:

        【解决方案3】:

        我找到了答案,可以通过两种方法解决,一种是在index.html中包含js文件,也可以像这样包含,也可以包含js和jquery。

        ngOnInit() {
        $(document).ready(function () {
          $.getScript('../../assets/frontend/js/app.js', function (w) { });
        }); }
        

        【讨论】:

          猜你喜欢
          • 2016-08-04
          • 2021-08-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-22
          • 2015-06-01
          相关资源
          最近更新 更多