Angular JS 2 - Bootstrap 导航栏下拉菜单不工作

Angular JS 2 - Bootstrap navbar dropdown not working

我正在使用 angular 2(使用 cli 创建项目)并安装了 bootstrap。

然后将 bootstrap CSS 添加到 angular-cli.json 然后样式有效但是当我有带有下拉菜单的导航栏时它不会打开它们。我认为是由于缺少 bootstrap.js 然后在 angular-cli.json 的脚本部分添加了它,它抱怨 jquery!!然后补充说。

它开始工作了,但我不确定我在做什么是对的。

粘贴 angular-cli.json 以供参考。

"styles": [
    "styles.css",
    "../node_modules/bootstrap/dist/css/bootstrap.css"
  ],
  "scripts": ["./js/jquery.js",     "../node_modules/bootstrap/dist/js/bootstrap.js"],

是的,它可能适合您,有时使用 Jquery 和 Angular 可能会导致问题。 bcz bootstrap.js 可能会在内部更改 dom 元素,因此在某些情况下可能会导致一些问题。

但我建议您使用 ng2-bootstrap module, which will allow your access Bootstrap components which are already written for angular2 way. here you can also find your Dropdown 组件。

我建议使用提供 Angular 2 与 Bootstrap 的原生集成的库。 https://ng-bootstrap.github.io library has excellent API and is easy to use. The good news is that it also has support for dropdowns as demonstrated here: https://ng-bootstrap.github.io/#/components/dropdown

有了上面提到的库,你不需要安装 jQuery 和 Bootstrap 的 JS(你只需要 CSS)并且下拉菜单非常容易使用(注意ngbDropdownngbDropdownToggle 指令):

<div ngbDropdown class="d-inline-block">
    <button class="btn btn-outline-primary" id="dropdownMenu1" ngbDropdownToggle>Toggle dropdown</button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenu1">
        <button class="dropdown-item">Action - 1</button>
        <button class="dropdown-item">Another Action</button>
        <button class="dropdown-item">Something else is here</button>
    </div>
</div>

嘿,甚至还有一个活生生的例子供您参考:http://plnkr.co/edit/mSV1qxTwLgL55L1kWmd9?p=preview

我浏览了 ng2-bootstrap 文档。没有看到导航栏已经完成了。当我看到它时会重构。

不过,我确实遇到了一个非常简单的教程,不需要您使用 jquery。 https://medium.com/@ct7/the-simple-way-to-make-a-mobile-angular-2-bootstrap-navbar-without-jquery-d6b3f67b037b

请注意,作者引用了媒体查询

@media(最小宽度:768px){...}

如果您已经拥有 bootstrap css 风格 link 则没有必要。
转到我的导航栏组件并添加必要的 属性 并单击处理程序

  isIn = false;

 toggleState() { // click handler for navbar toggle
    const bool = this.isIn;
    this.isIn = bool === false ? true : false;
 }

在导航栏 html 模板上添加了点击处理程序

 <button type="button" class="navbar-toggle" aria-expanded="false" aria-controls="navbar" (click)="toggleState()">

ngClass 添加到我想要折叠的 div

<div id="navbar" class="navbar-collapse collapse"
  [ngClass]="{'in':isIn}">

您只需将这些链接复制并粘贴到 index.html

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>