๐ ngx-smart-permissions
June 15, 2025 ยท View on GitHub
ngx-smart-permissions is a lightweight and smart Angular library for managing role-based and permission-based access control in Angular applications. Supports both standalone components and NgModules.
Built for Angular 17+ & 18+.
โจ Features
- โ Show/Hide UI based on permissions or roles
- โ
Reusable Directives:
*ngxHasPermission,*ngxHasRole - โ Built-in Route Guard for permission-based navigation
- โ Live permission switching (great for testing/admins)
- โ Support for Super Admin
- โ Lazy-loaded module support
- โ Fully compatible with Standalone Components
- โ
Easy setup with
provideNgxSmartPermissions(...)
๐ฆ Installation
npm install ngx-smart-permissions
๐ ๏ธ Setup
1. Register the providers
In main.ts:
import { provideNgxSmartPermissions } from 'ngx-smart-permissions';
bootstrapApplication(AppComponent, {
providers: [
provideNgxSmartPermissions({
redirectTo: '/unauthorized' // optional
})
]
});
Or inside an NgModule:
@NgModule({
imports: [
NgxSmartPermissionsModule
]
})
export class AppModule {}
๐ง Usage
โ
UI Directive: *ngxHasPermission
<!-- Show only if user has "edit-post" permission -->
<button *ngxHasPermission="'edit-post'">Edit</button>
<!-- Show if user has ANY of these -->
<div *ngxHasPermission="['admin', 'editor']">Admin Tools</div>
โ
Role Directive: *ngxHasRole
<div *ngxHasRole="'admin'">Welcome, Admin</div>
๐ Permission Guard
Protect routes by permission:
import { permissionGuard } from 'ngx-smart-permissions';
{
path: 'admin',
canActivate: [permissionGuard],
data: {
permission: 'access-admin'
}
}
๐ Set Permissions (e.g. after login)
In your AuthService or login component:
const permissions = ['view-dashboard', 'edit-user'];
const role = 'admin';
const isSuperAdmin = role === 'admin';
permissionService.switchPermissions(permissions, isSuperAdmin, role);
๐ซ Access Denied Page
Use redirectTo in provideNgxSmartPermissions() to control redirection for unauthorized access.
provideNgxSmartPermissions({ redirectTo: '/unauthorized' });
๐งช Testing
Basic unit tests are recommended for your permission logic.
You can spy on PermissionService methods for behavior tests.
๐ File Structure
src/
โโโ lib/
โโโ directives/
โ โโโ has-permission.directive.ts
โ โโโ has-role.directive.ts
โโโ guards/
โ โโโ permission.guard.ts
โโโ permission/
โ โโโ permission.service.ts
โ โโโ permission.config.ts
โ โโโ permissions.providers.ts
โโโ ngx-smart-permissions.module.ts
โโโ public-api.ts
โ Compatibility
- โ Angular 17 & 18
- โ
Supports both
NgModules&Standalone Components - โ Fully tree-shakable & side-effect free
๐ Live Demo
Check out the live demo on GitHub:
๐ ngx-smart-permissions Demo App
๐ License
MIT ยฉ Rami Shaikha