You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular导航项:如何实现首次点击同时跳转页面并打开下拉菜单?

Angular导航项组件:实现点击同时跳转并展开下拉菜单

问题描述

当前导航项组件首次点击仅跳转页面,第二次点击才会打开下拉菜单。目标是首次点击时同时完成页面跳转和下拉菜单展开。

问题根源

  1. <a>标签的routerLink会触发页面跳转,导致组件重新初始化,dropdownOpen状态被重置为false,跳转后下拉菜单无法自动展开。
  2. 原代码中NgbActiveOffcanvas未在构造函数中注入,调用dismiss()时会报错。
  3. 用户修改的代码未注入Router,且未处理页面跳转后状态丢失的问题,因此无效。

解决方案

步骤1:修改模板,阻止<a>标签默认跳转

避免<a>的默认跳转行为与div的点击事件冲突,统一由组件逻辑控制跳转:

<div (click)="handleToggleDropdown()">
  <a [routerLink]="route" (click)="$event.preventDefault()">{{ text }}</a>
</div>

步骤2:完善组件逻辑,处理路由与下拉状态

  • 注入Router和ActivatedRoute,用于判断当前路由并控制跳转。
  • 组件初始化时根据当前路由设置下拉初始状态,确保跳转后下拉保持展开。
  • 调整点击事件逻辑,区分当前是否在目标路由:不在则跳转,在则切换下拉状态。

修改后的组件代码:

import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveOffcanvas } from '@ng-bootstrap/ng-bootstrap';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'navigation-item',
  templateUrl: './navigation-item.component.html',
})
export class NavigationItemComponent implements OnInit {
  dropdownOpen = false;
  @Input() route?: string;
  @Input() text = '';
  @Input() hasDropdown = false;

  constructor(
    private activeOffcanvas: NgbActiveOffcanvas,
    private router: Router,
    private activatedRoute: ActivatedRoute
  ) {}

  ngOnInit(): void {
    // 初始化时判断当前路由是否匹配目标路由,设置下拉展开状态
    if (this.route) {
      this.dropdownOpen = this.router.isActive(this.route, { exact: true });
    }
  }

  toggleDropdown() {
    this.dropdownOpen = !this.dropdownOpen;
  }

  handleToggleDropdown() {
    if (this.hasDropdown && this.route) {
      const isCurrentRoute = this.router.isActive(this.route, { exact: true });
      
      if (!isCurrentRoute) {
        // 不在目标路由,执行跳转,跳转后组件初始化会自动展开下拉
        this.router.navigate([this.route]);
      } else {
        // 已在目标路由,直接切换下拉状态
        this.toggleDropdown();
      }
    } else {
      this.activeOffcanvas.dismiss();
    }
  }
}

效果说明

  • 首次点击导航项:若不在目标路由,会跳转至目标页面,同时下拉菜单自动展开(组件初始化时根据路由设置dropdownOpen为true)。
  • 已在目标路由时点击:直接切换下拉菜单的展开/收起状态。

内容的提问来源于stack exchange,提问作者Nataša Kunić

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 05:09:59