有没有办法在 ng2-bootstrap 中构建移动导航栏?

Is there a way to build the mobile nav bar in ng2-bootstrap?

我一直在实施 ng2-bootstrap 和 Angular2。

我不知道如何打开/关闭移动导航栏。

这是否还不受支持?还是我遗漏了什么?

更新,html:

<nav class="navbar navbar-default">
    <div class="container-fluid">

    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">
            <img src="/logo.png" />
        </a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
            <li router-active>
                <a [routerLink]=" ['Index'] ">Summary<span class="sr-only">(current)</span></a>
            </li>
            <li router-active>
                <a [routerLink]=" ['Portfolio'] ">Portfolio<span class="sr-only">(current)</span></a>
            </li>
            <li router-active>
                <a [routerLink]=" ['About'] ">About<span class="sr-only">(current)</span></a>
            </li>
        </ul>
        <form class="navbar-form navbar-left" role="search">
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
        <ul class="nav navbar-nav navbar-right">
            <li dropdown keyboardNav="true">
                <a href class="dropdown-toggle" role="button" aria-expanded="false" dropdownToggle>
                    <span class="glyphicon glyphicon-user" aria-hidden="true"></span>
                    Andrew Duncan 
                    <span class="caret"></span>
                </a>
                <ul class="dropdown-menu" role="menu">
                    <li role="menuitem"><a class="dropdown-item" href="#">Account Settings</a></li>
                    <li role="menuitem"><a class="dropdown-item" href="#">Another action</a></li>
                    <li role="menuitem"><a class="dropdown-item" href="#">Something else here</a></li>
                    <li class="divider dropdown-divider"></li>
                    <li role="menuitem"><a class="dropdown-item" href="#">Logout</a></li>
                </ul>
            </li>

        </ul>
    </div>
</div>

打字稿:

/*
 * Angular 2 decorators and services
 */
import { Component, ViewEncapsulation } from '@angular/core';
import { RouteConfig, Router } from '@angular/router-deprecated';

import { AppState } from './app.service';
import { Home } from './home';
import { RouterActive } from './router-active';
import { BUTTON_DIRECTIVES, DROPDOWN_DIRECTIVES } from '../../node_modules/ng2-bootstrap';
/*
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'app',
  pipes: [ ],
  providers: [ ],
  directives: [ 
    RouterActive, 
    BUTTON_DIRECTIVES,
    DROPDOWN_DIRECTIVES ],
  encapsulation: ViewEncapsulation.None,
  styles: [
    require('./app.css')
  ],
  template: require('./app.html')
})
@RouteConfig([
  { path: '/',      name: 'Index', component: Home, useAsDefault: true },
  { path: '/home',  name: 'Home',  component: Home },
  // Async load a component using Webpack's require with es6-promise-loader and webpack `require`
  { path: '/about', name: 'About', loader: () => require('es6-promise!./about')('About') },
  { path: '/portfolio', name: 'Portfolio', loader: () => require('es6-promise!./portfolio')('Portfolio') }
])
export class App {
  angularclassLogo = 'assets/img/angularclass-avatar.png';
  loading = false;
  url = 'https://twitter.com/AngularClass';

  constructor(
    public appState: AppState) {

  }

  ngOnInit() {
    console.log('Initial App State', this.appState.state);
  }

}

/*
 * Please review the https://github.com/AngularClass/angular2-examples/ repo for
 * more angular app examples that you may copy/paste
 * (The examples may not be updated as quickly. Please open an issue on github for us to update it)
 * For help or questions please contact us at @AngularClass on twitter
 * or our chat on Slack at https://AngularClass.com/slack-join
 */

您需要包含并使用折叠指令

首先导入指令
import { CollapseDirective } from 'ng2-bootstrap'

将其包含在您的组件指令中
@Component({ directives: [CollapseDirective] })

编辑:正如 Akkusativobjekt 在评论中指出的那样,指令(在 angular 2 的当前稳定版本中)不再放置在 @Component 属性中。
它们包含在 NgModule 属性中。

@NgModule({ declarations: [CollapseDirective] })

然后在您的控制器中创建一个变量来跟踪它是否已折叠
export class MyController { public isCollapsed: boolean = true; }

在您的模板中,看起来像这样的行
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" >
你会想要切换变量
<button type="button" class="navbar-toggle collapsed" (click)="isCollapsed = !isCollapsed" >

在您的模板中,您还需要更改显示
的行 <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> 包含指令
<div id="navbar" class="navbar-collapse collapse" [collapse]="isCollapsed">

Documentation for ng2-bootstrap collapse
Example of using the collapse directive in html
Documentation for NgModule

通过向可折叠目标 div:

添加相同的 data-toggle 和 data-target 属性,我能够在我的 angular2 项目中直接使用 bootstrap4/jquery 来做到这一点
<nav class="navbar navbar navbar-dark bg-inverse navbar-sticky-top clearfix">
  <div class="clearfix">
    <a class="navbar-brand" href="#">MCR</a>
    <button class="navbar-toggler hidden-sm-up float-xs-right" type="button" data-toggle="collapse"
        data-target="#exCollapsingNavbar2" aria-controls="exCollapsingNavbar2" aria-expanded="false"
        aria-label="Toggle navigation">
    </button>
  </div>
  <div class="collapse navbar-toggleable-xs" id="exCollapsingNavbar2" data-toggle="collapse" data-target="#exCollapsingNavbar2">
  <ul class="nav navbar-nav">
    <li class="nav-item">
      <a routerLink="/home" routerLinkActive="active" class="nav-link" href="#">Home</a>
    </li>
    <li class="nav-item">
      <a routerLink="/collection" routerLinkActive="active" class="nav-link" href="#">Collection</a>
    </li>
  </ul>
</div>

我希望这可以帮助我为此苦苦挣扎的人。感谢以上所有让我走上正轨的人。

虽然 Seth 的解决方案按原样运行得非常好,但我修改了折叠逻辑。我没有使用点击事件,而是订阅了路由器事件,仅在成功导航后才折叠菜单。

export class NavMenuComponent implements OnDestroy {
    public isCollapsed: boolean = true;
    private subscription: Subscription;

    constructor(private router: Router) {  
        this.subscription = this.router.events.subscribe(s => {
            if (s instanceof NavigationEnd) {
                this.isCollapsed = true;
            }
        });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

这是导航栏的限制 (https://github.com/valor-software/ngx-bootstrap/issues/540)。所以你需要操作DOM元素。

<div class="navbar-header page-scroll">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" routerLink="/">
        <img src="assets/images/logo.png">
    </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
    <ul class="nav navbar-nav navbar-right" >
        <li class="hidden">
            <a></a>
        </li>
        <li><a routerLink="/" (click)="onMenuClick()">Home</a></li>
        <li><a routerLink="/about" (click)="onMenuClick()">About</a></li> 
    </ul>
</div>

在 .ts 文件上,您的最少代码应该是:

import { Component, ElementRef, Renderer } from '@angular/core';
export class HeaderComponent {
    constructor(private el: ElementRef, private renderer: Renderer) {
    }
    onMenuClick() {
        //this.el.nativeElement.querySelector('.navbar-ex1-collapse')  get the DOM
        //this.renderer.setElementClass('DOM-Element', 'css-class-you-want-to-add', false) if 3rd value is true 
        //it will add the css class. 'in' class is responsible for showing the menu, remove it.
        this.renderer.setElementClass(this.el.nativeElement.querySelector('.navbar-ex1-collapse'), 'in', false);        
    }
}