gpt4 book ai didi

angular - 在 Angular 7 中导入 bootstrap 时,Bootstrap 4 下拉菜单中断

转载 作者:行者123 更新时间:2023-12-05 05:12:39 24 4
gpt4 key购买 nike

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

我正在尝试使用 vanilla Bootstrap JS 和 jQuery,因为我需要 Bootstrap 的 toasts 而其他库(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 创建一个 Angular 应用
  2. 安装 Bootstrap 和 Bootstrap 类型:
    • npm install --save bootstrap @types/bootstrap
    • @types/bootstrap 需要 popper.js 作为依赖项。
  3. 包括 Bootstrap 4 CSS 和 JS 文件
  4. 包含 Popper JS UMD 文件
  5. 在某处添加 import 'bootstrap'; 以告诉 typescript 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';

但是,如果我删除它,Typescript 在我想做一些 Bootstrap jQuery 时会尖叫,比如显示 toasts 或工具提示:

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

最佳答案

您在这里遇到的问题是因为 typescript 编译器。为了避免这种情况,您可以在基本 JS 文件中初始化工具提示和其他元素。您需要导入此文件,以便在 Assets 文件夹中创建它(并将其链接到您的 index.html)或在其他位置创建它并在 scripts 部分中提及它你的 angular.json

要初始化工具提示,这个 JS 文件的内容应该是:

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

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

如果你想在 Angular 流程中的特定时刻执行此操作,请将调用包装在一个函数中,如下所示:

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

要在 Typescript 文件中调用它,您需要先声明该函数。例如,要在 ngOnInit() 中初始化工具提示:

declare function tooltip();
ngOnInit() {
tooltip();
}

这样你就不需要在任何地方import 'bootstrap';,所以你不会破坏你的其他组件。

关于angular - 在 Angular 7 中导入 bootstrap 时,Bootstrap 4 下拉菜单中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54407072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com