Reputation: 33
How can hide the name in the navigation menu for specific users. Namely, I want to hide the "Administration" for users with the "User" role installed. That is, if the user logged on with the user role, then the name "Administration" in the menu list will be hidden for him.
ts:
import { Component, OnInit } from '@angular/core';
import {AuthService} from "../../services/auth/auth.service";
export interface RouteInfo {
path: string;
title: string;
icon: string;
class: string;
}
export const ROUTES: RouteInfo[] = [
{ path: 'notes', title: 'Notes', icon: 'ti-comment', class: '' },
{ path: 'contacts', title: 'Contacts', icon:'ti-info', class: '' },
{ path: 'users', title: 'Users', icon:'ti-user', class: '' },
{ path: 'user_notes', title: 'Notes (World)', icon:'ti-world', class: '' },
{ path: 'admins', title: 'Administration', icon:'ti-server', class: '' }
];
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {
public menuItems: any[];
constructor(
public authService:AuthService
) {}
ngOnInit() {
this.menuItems = ROUTES.filter(menuItem => menuItem);
}
}
html:
...
<li *ngFor="let menuItem of menuItems" routerLinkActive="active" class="{{menuItem.class}}">
<a [routerLink]="[menuItem.path]">
<i class="{{menuItem.icon}}"></i>
<p>{{menuItem.title}}</p>
</a>
</li>
...
Upvotes: 3
Views: 477
Reputation: 286
First it would make sense to get the users role from the AuthService
and then filter the routes based on his role. I assume the AuthService
makes an asynchronous call to an API.
In a way like this:
ngOnInit() {
this.authService.getCurrentUser().subscribe(user => {
this.menuItems = ROUTES.filter(menuItem => {
return menuItem.path !== 'admins' || menuItem.path === 'admins' && user.role === 'admin';
});
});
}
Upvotes: 1
Reputation: 5462
You can add one more field role
in ROUTES
. While filtering menus you can check if currentRole
is allowed for that menu item.
export const ROUTES: RouteInfo[] = [
{ path: 'notes', title: 'Notes', icon: 'ti-comment', class: '', role:[user, admin] },
{ path: 'contacts', title: 'Contacts', icon:'ti-info', class: '', role:[user, admin] },
{ path: 'users', title: 'Users', icon:'ti-user', class: '', role:[user, admin] },
{ path: 'user_notes', title: 'Notes (World)', icon:'ti-world', class: '', role:[user, admin] },
{ path: 'admins', title: 'Administration', icon:'ti-server', class: '', role:[admin] }
];
@Component({
...
})
export class SidebarComponent implements OnInit {
...
currentRole: string; // set value in it in constructor
constructor(public authService:AuthService) {
this.currentRole = 'user'; // change value on the basis of login
}
ngOnInit() {
this.menuItems = ROUTES.filter(menuItem => menuItem.role.includes(this.currentRole));
}
}
Upvotes: 2