I have two users on my website, 'user' and 'admin', I want to show some items to user and some items to admin, and i want to add dynamically items to menu from a component
The server can return different items according to the account's authority
Hi @trumanone1, kindly search through the issues and check out the docs, menu-related questions were discussed here a couple of times. Thanks!
I had the same issue myself. I looked at the previous discussions on the topic, but ended up using a different solution.
In pages.component.ts change the input to the nb-menu component to use a function instead of a variable:
<nb-menu [items]="getMenu()"></nb-menu>
Add the new function:
getMenu() {
return this.menuVisibility(MENU_ITEMS, 'Admin', this.isAdmin());
}
Add the function to be evaluated:
isAdmin() {
// your code goes here
return true;
}
Helper function:
menuVisibility(menu, title, visible) {
let newmenu = menu;
let index = menu.findIndex(v => v.title == title);
let menu_filter = menu.filter(v => v.title == title);
if ((menu_filter.length > 0) && (index >= 0)) {
menu_filter[0].hidden = !visible;
newmenu = [
...menu.slice(0, index),
menu_filter[0],
...menu.slice(index + 1),
]
}
return newmenu;
}
This code will hide the menu with title 'Admin' if the isAdmin() function evaluates to false.
this solution worked for me Thanks :)
hi @Ezeon solution worked but goes to infinite loop
@SalahudinMalik
The solution works by defining the full menu in 'MENU_ITEMS' and then using the function getMenu() to filter the menu items. I'm not sure how this could cause a loop. I'm using this code successfully in one of my projects.
If you could post your code, I'll be happy to take a look.
This is good, however, my use case is different. I have multiple companies with different user roles. So for Company A I want to display Menu A, B, C while Company B will have Menu D, E, F. Company A has User X and User Y where User X has access to Menu B and User Y has access to Menu A and Menu C. Company B has User M and User N where User M has access to Menu D and E and User N has access to Menu F. My thought is based on the login, I can fetch Jason using Http and then load this json file into menu items. Any direction would be most appreciated.
Most helpful comment
I had the same issue myself. I looked at the previous discussions on the topic, but ended up using a different solution.
In pages.component.ts change the input to the nb-menu component to use a function instead of a variable:
<nb-menu [items]="getMenu()"></nb-menu>Add the new function:
Add the function to be evaluated:
Helper function:
This code will hide the menu with title 'Admin' if the isAdmin() function evaluates to false.