gpt4 book ai didi

javascript - 为什么 @ViewChild(NgbDropdown) 在我的组件中不起作用?

转载 作者:行者123 更新时间:2023-12-02 03:01:42 24 4
gpt4 key购买 nike

我想扩展 ng-Boostrap 的下拉功能,通过按浏览器的后退按钮(在移动设备上)来关闭菜单。但是 this.dropdown 在 hide 函数中是未定义的。为什么?

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);
}
}
}
}

解决方法:

在 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);
}
}
}

最佳答案

尝试

@ViewChild('dropdownRef', {static:false, read: NgbDropdown}) dropdown: NgbDropdown;

关于javascript - 为什么 @ViewChild(NgbDropdown) 在我的组件中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59836293/

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