Javascript 为什么@ViewChild(NgbDropdown)不在我的组件中工作?
我想扩展ng Boostrap的下拉功能,通过按下浏览器后退按钮(在手机上)来关闭菜单。 但hide函数中未定义此.dropdown。为什么?Javascript 为什么@ViewChild(NgbDropdown)不在我的组件中工作?,javascript,angular,ng-bootstrap,Javascript,Angular,Ng Bootstrap,我想扩展ng Boostrap的下拉功能,通过按下浏览器后退按钮(在手机上)来关闭菜单。 但hide函数中未定义此.dropdown。为什么? import {Component, Input, ViewChild} from '@angular/core'; import {NgbDropdown} from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-mobile-dropdown', templat: '&l
import {Component, Input, ViewChild} from '@angular/core';
import {NgbDropdown} from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-mobile-dropdown',
templat: '<div ngbDropdown class="menu" [placement]="placement" (openChange)="openChange($event)">
<span class="menu-btn" ngbDropdownToggle><i [class]="btnIcon"></i><span *ngIf="btnLabel">{{btnLabel}}</span></span>
<div ngbDropdownMenu>
<a ngbDropdownItem *ngFor="let item of actions" class="dropdown-item" (click)="item.action()">{{item.label}}</a>
</div>
</div>
'
})
export class MobileDropdownComponent{
@ViewChild(NgbDropdown,{static:false}) dropdown: NgbDropdown;
@Input() placement: string;
@Input() btnIcon: string;
@Input() btnLabel: string;
@Input() actions: Array<any>;
hide(){
console.log('closing', this.dropdown);
window.removeEventListener('popstate', this.hide);
this.dropdown.close();
}
openChange(opened: boolean) {
if (opened) {
window.history.pushState('ddOpen',null,null);
window.addEventListener('popstate',this.hide);
} else {
if(history.state === 'ddOpen'){
window.history.back();
window.removeEventListener('popstate', this.hide);
}
}
}
}
在声明模板引用变量的文本之前添加#
试着这样做:
.html
试一试
它没有帮助:(当调用
hide()
时?window.addEventListener('popstate',this.hide');所以按浏览器后退按钮。。。
openChange(opened: boolean) {
const self=this;
function hide(){
console.log('closing', self.dropdown, self.actions);
window.removeEventListener('popstate', hide);
self.dropdown.close();
}
if (opened) {
window.history.pushState('ddOpen',null,null);
window.addEventListener('popstate',hide);
} else {
if(history.state === 'ddOpen'){
window.history.back();
window.removeEventListener('popstate', hide);
}
}
}
<div #dropdownRef ngbDropdown class="menu" [placement]="placement" (openChange)="openChange($event)">
@ViewChild('dropdownRef',{static:false}) dropdown: NgbDropdown;
@ViewChild('dropdownRef', {static:false, read: NgbDropdown}) dropdown: NgbDropdown;