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

Angular中如何为左侧非主菜单的按钮配置对应导航链接

Solution

First, let's fix the core issue: your menupath Map is currently a local variable inside the constructor, so your template can't access it at all. We need to rework this to make the Map available to the template, then bind the correct route path to routerLink.

Step 1: Make the Route Map Accessible to the Template

Move the menupath Map from the constructor to be a class property of your component. This lets the template reference it directly:

import { Component, Input, OnInit } from '@angular/core'; 

@Component({ 
  selector: 'apm-menu-resource', 
  templateUrl: './menu-resource.component.html', 
  styleUrls: ['./menu-resource.component.less'] 
}) 
export class MenuResourceComponent implements OnInit { 
  @Input() public elements = []; 
  // Define the route map as a class property
  public menuRouteMap = new Map<string, string>();

  constructor() { 
    // Populate the route map here
    this.menuRouteMap.set('General', '/Adigem/config/general'); 
    this.menuRouteMap.set('Messaging', '/Adigem/config/messaging'); 
    this.menuRouteMap.set('Server', '/Adigem/config/email/server'); 
    this.menuRouteMap.set('Alerting', '/Adigem/config/email/alert'); 
    this.menuRouteMap.set('Network', '/Adigem/config/network'); 
    this.menuRouteMap.set('Inventory', '/Adigem/config/inventory'); 
    this.menuRouteMap.set('External port', '/Adigem/config/snmp/external-port'); 
    this.menuRouteMap.set('Cloud Data', '/Adigem/config/clouddata'); 
    this.menuRouteMap.set('Performance', '/Adigem/config/Performance'); 
    this.menuRouteMap.set('CFG', '/Adigem/config/cfg'); 
    this.menuRouteMap.set('System', '/Adigem/config/system'); 
  } 

  ngOnInit() { } 
}

Update your HTML template to use the menuRouteMap to fetch the corresponding path for each menu item. We'll add a fallback route (like the root /) to handle cases where a resource isn't found in the Map, preventing broken navigation:

<div class="row-styles" id="elements" *ngFor="let item of elements"> 
  <button *ngIf="item.action !== NO_ACCESS" class="inner-children" routerLinkActive="active" id="inner-children" 
          [routerLink]="menuRouteMap.get(item.resource) || '/'"> 
    <span>{{item.resource}}</span> 
  </button> 
</div>

Quick Notes:

  • The || '/' fallback ensures that if an unexpected item.resource value comes through, the button will navigate to the root route instead of an undefined path.
  • Double-check that your NO_ACCESS constant is defined in a place the template can access it (either as a component class property or a globally imported constant).

内容的提问来源于stack exchange,提问作者Varnika Gautam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 06:44:09