在Angular 7中导入引导程序时,Bootstrap 4下拉菜单中断

时间:2019-01-28 17:12:33

标签: angular bootstrap-4 popper.js

我在Angular 7应用中遇到了这个问题。我无法使用纯Bootstrap CSS / JS和Popper.js复制它。

我正在尝试使用香草Bootstrap JS和jQuery,因为我需要Bootstrap的吐司,而其他库(ng-bootstrapngx-bootstrap)暂时不支持吐司。

最小(非)工作示例

https://github.com/Crocmagnon/angular-bootstrap4-dropdown-issue

使用npm run start

运行它

在Popper.js存储库中发布的链接

我试图问开发商,但他一无所知:https://github.com/FezVrasta/popper.js/issues/748

重现问题的步骤

重现该示例:

npm i -g @angular/cli
git clone https://github.com/Crocmagnon/angular-bootstrap4-dropdown-issue.git
cd angular-bootstrap4-dropdown-issue
npm i
ng serve

要从头开始复制:

  1. 使用ng-cli创建一个角度应用程序
  2. 安装引导程序和引导程序类型:
    • npm install --save bootstrap @types/bootstrap
    • @types/bootstrap需要popper.js作为依赖项。
  3. 包括Bootstrap 4 CSS和JS文件
  4. 包括Popper JS UMD文件
  5. 在某处添加import 'bootstrap';来告诉打字稿jQuery .tooltip()函数存在
  6. 尝试在导航栏中使用Bootstrap 4下拉菜单

angular.json的相关摘录:

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "node_modules/@fortawesome/fontawesome-free/css/all.css",
  "src/styles.scss"
],
"scripts": [
  "node_modules/jquery/dist/jquery.slim.js",
  "node_modules/popper.js/dist/umd/popper.js",
  "node_modules/bootstrap/js/dist/util.js",
  "node_modules/bootstrap/js/dist/alert.js",
  "node_modules/bootstrap/js/dist/button.js",
  "node_modules/bootstrap/js/dist/carousel.js",
  "node_modules/bootstrap/js/dist/collapse.js",
  "node_modules/bootstrap/js/dist/dropdown.js",
  "node_modules/bootstrap/js/dist/modal.js",
  "node_modules/bootstrap/js/dist/scrollspy.js",
  "node_modules/bootstrap/js/dist/tab.js",
  "node_modules/bootstrap/js/dist/toast.js",
  "node_modules/bootstrap/js/dist/tooltip.js",
  "node_modules/bootstrap/js/dist/popover.js"
]

预期的行为是什么?

下拉菜单应该切换

出了什么问题?

下拉菜单根本不会切换

评论

我试图在angular.json文件中包含Popper ESM文件。现在一切正常,除了控制台出现错误。

Uncaught SyntaxError: Unexpected token export

我在这里想念什么吗?

编辑

main.ts中的此语句似乎打破了下拉列表:

import 'bootstrap';

但是,如果我删除它,当我想做一些Bootstrap jQuery(如显示吐司或工具提示)时,Typescript会尖叫:

$(() => {
  $('[data-toggle="tooltip"]').tooltip();
});

2 个答案:

答案 0 :(得分:2)

您遇到的问题是因为打字稿编译器。为了避免这种情况,您可以在基本JS文件中初始化工具提示和其他元素。您将需要导入此文件,因此可以在资产文件夹中创建该文件(并在index.html中进行链接),也可以在其他位置创建该文件,并在scripts的{​​{1}}部分中进行提及。

要初始化工具提示,此JS文件的内容为:

angular.json

这将在文档准备就绪时初始化所有工具提示。

如果您想在Angular流中的特定时刻执行此操作,请将调用包装成如下函数:

$(() => {
  $('[data-toggle="tooltip"]').tooltip();
});

要在Typescript文件中调用它,您需要首先声明该函数。例如,要初始化function tooltip() { $(() => { $('[data-toggle="tooltip"]').tooltip() }) } 中的工具提示:

ngOnInit()

这样,您无需在任何地方declare function tooltip(); ngOnInit() { tooltip(); } ,因此不会破坏其他组件。

答案 1 :(得分:1)

我正在使用最新版本的angular-cli。

首先,从此link下载我的github项目,并在@descriptions.each do |description|中运行cmd(这样,所有依赖项都会添加到您的系统中),然后运行npm install,这将导航到http://localhost:4200/

如果这样做,您的问题就解决了。

如果要在项目中使用ng-serve

jquery-syntex中键入此命令

cmd

并将此概要添加到您的app.component.ts

npm install jquery --save 
npm install @types/jquery --save 

第二个问题

如果要在设备上使用import $ from 'jquery'; ,请使用ngx-bootstrap

谢谢!