Hi,
I am using metronic angular version 8.2.2. I dynamically load the sidebar-menu but when I refresh my page, the relevant menu is not selected by default. What to do ?
Hi,
If you are using a static menu and Angular Router, you can use Angular's routerLinkActive directive to set the active state for a menu item based on the current route.
If you are dealing with a dynamic menu loaded and you still want to highlight the active menu item based on the current route, you can use a combination of Angular's routerLink and routerLinkActive directives along with custom logic in your component to determine the active state. Here's an example:
Assuming you have a dynamic menu loaded from a variable like this:
// your-menu.service.ts
import { Injectable } from "@angular/core";
@Injectable({
providedIn: "root",
})
export class YourMenuService {
getMenuItems(): MenuItem[] {
// Retrieve your dynamic menu items from a variable or API
return [
{ path: "/dashboard", label: "Dashboard" },
{ path: "/profile", label: "Profile" },
// Add more menu items as needed
];
}
}
interface MenuItem {
path: string;
label: string;
}
// your-menu.component.ts
import { Component, OnInit } from "@angular/core";
import { YourMenuService } from "path-to-your-menu-service";
import { ActivatedRoute } from "@angular/router";
@Component({
selector: "app-your-menu",
templateUrl: "./your-menu.component.html",
styleUrls: ["./your-menu.component.css"],
})
export class YourMenuComponent implements OnInit {
menuItems: MenuItem[] = [];
constructor(private menuService: YourMenuService, private route: ActivatedRoute) {}
ngOnInit(): void {
// Load dynamic menu items
this.menuItems = this.menuService.getMenuItems();
}
// Custom logic to determine whether the menu item is active
isMenuItemActive(path: string): boolean {
return this.route.snapshot.routeConfig?.path === path;
}
}
<!-- your-menu.component.html -->
</p><ul>
<li *ngFor="let menuItem of menuItems" [class.active]="isMenuItemActive(menuItem.path)">
<a [routerLink]="menuItem.path">{{ menuItem.label }}</a>
</ul>