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() { } }
Step 2: Bind the Correct Route to routerLink
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 unexpecteditem.resourcevalue comes through, the button will navigate to the root route instead of an undefined path. - Double-check that your
NO_ACCESSconstant 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
相关产品推荐
相关产品推荐

