Back

Technologies:

javascriptjavascript
htmlhtml
avatar
Tolerim
4 minutes ago

How does the Permissions Navbar (ngxPermissions) work in Angular?

In an Angular project using ngx-permissions, I'm working on granting permissions to test users 'ADMIN' and 'USER' to view items in the navbar. I want the 'ADMIN' user to have access to all items in the navbar, whereas the 'USER' user should only be able to see one item. I'm currently using ngxPermissions to achieve this, but I'm struggling to limit the 'USER' user to only one navbar item. The Navbar.ts file contains the list of navigation items, and in default-layout.component.ts, the permissions for 'ADMIN' and 'USER' are loaded. Currently, using ngxPermissionsOnly with ['ADMIN'] grants access to all items, but how can I limit the 'USER' user to only one item in [navItems]?
Answers(1)
avatar
Tolerim
4 minutes ago
Verified Answer
To set only one of the items in [navItems] to USER, you can use NgxPermissions structural directive. Here's an example:
<ul>
  <li *ngxPermissionsOnly="['ADMIN']; else userNav">Admin Navigation Item</li>
</ul>

<ng-template #userNav>
  <ul>
    <li>Regular Navigation Item</li>
  </ul>
</ng-template>
In this example, we are using the *ngxPermissionsOnly directive to display the "Admin Navigation Item" only to users with the "ADMIN" role. For all other users, the "Regular Navigation Item" is displayed using the ng-template syntax and the else keyword. In your case, you can modify your default-layout.component.html file to include an *ngxPermissionsOnly directive on the specific nav item you want to show to the "USER" role like this:
<perfect-scrollbar [config]="perfectScrollbarConfig">
  <!--  [perfectScrollbar]="perfectScrollbarConfig"-->
  <c-sidebar-nav *ngxPermissionsOnly="['ADMIN']" [navItems]="navItems" dropdownMode="close">
    <ng-container *ngFor="let navItem of navItems">
      <ng-container *ngIf="navItem.name === 'Item only for USER'">
        <li *ngxPermissionsOnly="['USER']">{{ navItem.name }}</li>
      </ng-container>
    </ng-container>
  </c-sidebar-nav>
</perfect-scrollbar>
In this example, we are using *ngxPermissionsOnly directive to display the specific nav item Item only for USER only to users with the "USER" role.
;