我尝试使用Angular CLI创建的Angular 4 App中的navbar组件内部使用bootstrap 4 collapse
方法。
问题如下。我使用以下代码导入jquery和bootstrap:
import * as $ from 'jquery';
import 'bootstrap';
然后让这个事件处理程序在单击链接时折叠导航栏:
$('#navbarToggleArea .nav-link').on('click', function () {
$('#navbarToggleArea').collapse('hide');
});
使用ng serve
或ng build
命令成功编译代码,但在运行时失败,就好像bootstrap插件未添加到jQuery中一样。当调用collapse
函数时,抛出错误:
vendor.bundle.js:60854 ERROR TypeError: WEBPACK_IMPORTED_MODULE_1_jquery (...)。collapse不是函数
我的问题是:我应该如何配置以消除此错误?
答案 0 :(得分:0)
要实现折叠,请使用angular:
<div class="navbar-collapse collapse" [class.in]='collapsed'>
关于'humburger'
<span [class.open]="collapsed" id="humburger" (click)="collapsed=!collapsed">
在课堂上:
collapse:boolean
;
答案 1 :(得分:0)
在我的页面myPage
中实现此目的的角度方式Bootstrap Navbar
<nav class="navbar navbar-toggleable-md navbar-light bg-faded navbar-fixed-top">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false"
aria-label="Toggle navigation" (click)="isActive = !isActive">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<div class="collapse navbar-collapse" id="navbarNavDropdown" [ngClass] = "{show : isActive}"> // ngClass used here
<ul class="navbar-nav">
<li class="nav-item dropdown [routerLinkActive]="['active']" appDropdown"> // directive used here
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown link
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
</ul>
</div>
</nav>
appDropdown指令
import {Directive, HostListener, HostBinding} from '@angular/core';
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective {
private isOpen:boolean = false;
@HostBinding('class.open') get opened(){
return this.isOpen;
}
constructor() { }
@HostListener('click')open(){
this.isOpen = true;
}
@HostListener('mouseleave')close(){
this.isOpen = false;
}
}