我有 Angular 导航项组件:
<div(click)="handleToggleDropdown()">
<a[routerLink]="route">{{ text }}</a>
</div>
import { Component, Input } from '@angular/core';
import { NgbActiveOffcanvas } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'navigation-item',
templateUrl: './navigation-item.component.html',
})
export class NavigationItemComponent {
dropdownOpen = false;
@Input() route?: string;
@Input() text = '';
@Input() hasDropdown = false;
toggleDropdown() {
this.dropdownOpen = !this.dropdownOpen;
}
handleToggleDropdown() {
if (this.hasDropdown) {
this.toggleDropdown();
} else {
this.activeOffcanvas.dismiss();
}
}
}
现在,第一次单击导航项将路由到页面,第二次单击将打开下拉菜单。 第一次单击导航项是否有可能同时路由到页面并打开下拉菜单?
我尝试过这样的:
handleToggleDropdown() {
if (this.hasDropdown) {
if (!this.dropdownOpen) {
this.router.navigate([this.route]);
}
this.toggleDropdown();
} else {
this.activeOffcanvas.dismiss();
}
}
但是也不起作用
也许你可以听导航事件来做到这一点:
constructor(private router: Router) {
this.router.events.pipe(tap(() => {
if (event instanceof NavigationEnd) {
// After navigation ends, toggle the dropdown if it was supposed to open
this.toggleDropdown();
}
}), takeUntilDestroy()).subscribe();
}