【问题标题】:Utilizing Bootstrap .modal() JQuery method in Angular App在 Angular App 中使用 Bootstrap .modal() JQuery 方法
【发布时间】:2018-01-17 15:48:49
【问题描述】:

关于 .modal 方法,我在 Bootstrap 4 和 NPM/Angular CLI 方面遇到了一些功能错误

错误:TypeError: $(...).modal is not a function

main.ts:

import * as $ from 'jquery';
import * as bootstrap from 'bootstrap';

app.components.ts:

import * as $ from 'jquery';
import * as bootstrap from 'bootstrap';

...

$('#new-product-modal').modal('hide');

app.component.html:

<div class="modal fade" id="new-product-modal" tabindex="-1" role="dialog" aria-labelledby="new-product-modal" aria-hidden="true">

.angular-cli.json:

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

package.json:

"bootstrap": "^4.0.0-beta.3",
...
"jquery": "^3.2.1",
...
"popper.js": "^1.12.9",

它不会在 Visual Studio Code 或 ng build/serve 命令中引发错误。但它会引发控制台错误并且不会隐藏模式。模态的所有其他功能都按预期执行,例如 data-dismiss="modal" 等。有什么想法吗?

【问题讨论】:

    标签: jquery angular twitter-bootstrap angular-cli


    【解决方案1】:

    第一步,您需要通过 npm 命令安装 jquerybootstrap

    其次你需要在组件中添加declare var $ : any;重要

    并且可以在 onSave() 方法上使用$('#myModal').modal('hide');

    演示https://stackblitz.com/edit/angular-model-bootstrap-close?file=src/app/app.component.ts

    【讨论】:

    • any 类型声明$ 违背了TypeScripts 类型检查的目的,它不是一种解决方案,而是一种解决方法。您会考虑提供替代解决方案吗?
    【解决方案2】:

    也许你的模态元素在你调用后正在渲染

    $('#new-product-modal').modal('hide');
    

    尝试在文档就绪功能中使用您的脚本,例如

    $(function(){
      $('#new-product-modal').modal('hide');
    });
    

    【讨论】:

    • 这样做会给我一个额外的黄色警告:jQuery.Deferred exception: $(...).modal is not a function 以及同样的错误。
    • 如果你仍然觉得 modal is not a function,那么你导入 bootstrap 的方式可能有问题。
    • 这也是我倾向于的。我找到了import语句import * as bootstrap from 'bootstrap';,这样对吗?
    【解决方案3】:

    第一步你需要通过 npm 命令安装 jquery 和 bootstrap。

    其次,您需要添加 declare var $ : any;在组件中(重要)

    并且使用可以使用 $('#myModal').modal('hide');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      相关资源
      最近更新 更多