DEV Community

Cover image for Roles in an Angular app: one table instead of if (admin) everywhere
Roberto Russo
Roberto Russo

Posted on

Roles in an Angular app: one table instead of if (admin) everywhere

Every admin dashboard I've worked on had the same problem sooner or later. Someone writes *ngIf="user.role === 'admin'" in a template, someone else adds a guard with its own list of roles, and a month later the menu still shows Billing to people who can't open it. Then the product adds a fourth role and you get to grep the whole app.

In the last dashboard I built (Angular 22, signals, zoneless) I tried to fix that with something boring: a single table that says what each role can do, and everything else asks that table. Menus, routes, buttons, even the mock backend. It's been working well, so here's how it's put together.

If you want to poke at it first, there's a live demo. Open the account menu, pick "Preview as role", then Viewer, and watch half the app disappear.

The table

Components never ask "is this an admin?". They ask "can the current user do X?", and the answer lives in one file:

// core/auth/permissions.ts
export type Permission =
  | 'users.write'       // invite and edit customers
  | 'users.delete'      // delete customers
  | 'reports.write'     // save, rename, delete reports
  | 'billing.view'      // open the Billing page
  | 'billing.manage'    // change plan, payment method
  | 'team.manage';      // invite members, change roles

export const ROLE_PERMISSIONS: Record<UserRole, readonly Permission[]> = {
  owner:  ['users.write', 'users.delete', 'reports.write', 'billing.view', 'billing.manage', 'team.manage'],
  admin:  ['users.write', 'users.delete', 'reports.write', 'billing.view', 'team.manage'],
  member: ['users.write', 'reports.write'],
  viewer: [],
};

export function roleCan(role: UserRole | null | undefined, permission: Permission): boolean {
  return !!role && ROLE_PERMISSIONS[role].includes(permission);
}
Enter fullscreen mode Exit fullscreen mode

Permission being a union means 'billing.veiw' doesn't compile. And when someone asks "can members delete customers?", the answer is in the file above instead of in twelve templates.

A service with a signal in it

@Injectable({ providedIn: 'root' })
export class AccessService {
  private readonly auth = inject(AuthService);

  readonly role = computed<UserRole | null>(() => this.auth.user()?.role ?? null);

  can(permission: Permission): boolean {
    return roleCan(this.role(), permission);
  }
}
Enter fullscreen mode Exit fullscreen mode

Nothing clever. The nice part is that can() reads a signal, so if you call it from a template or a computed it reacts on its own when the role changes. No subscriptions, no async pipe.

Menus

Each nav item can say which permission it needs:

// layout/navigation.ts
export interface NavItem {
  label: string;
  path: string;
  icon: IconName;
  permission?: Permission;
}

export const NAVIGATION: NavSection[] = [
  { items: [{ label: 'Overview', path: '/overview', icon: 'layout-dashboard' } /* … */] },
  {
    title: 'Account',
    items: [
      { label: 'Billing', path: '/billing', icon: 'credit-card', permission: 'billing.view' },
      { label: 'Settings', path: '/settings', icon: 'settings' },
    ],
  },
];

export function allowedNavigation(can: (p: Permission) => boolean): NavSection[] {
  return NAVIGATION
    .map((section) => ({ ...section, items: section.items.filter((i) => !i.permission || can(i.permission)) }))
    .filter((section) => section.items.length > 0);
}
Enter fullscreen mode Exit fullscreen mode

and the sidebar is one line:

protected readonly sections = computed(() => allowedNavigation((p) => this.access.can(p)));
Enter fullscreen mode Exit fullscreen mode

I use the same function for the command palette and for the links on the 404 page.

Routes, and keeping the URL

Hiding the menu entry doesn't stop anyone from pasting /billing into the address bar, so the route needs a guard. What I didn't want was the usual redirect to /forbidden, where the URL changes and a refresh takes you to the wrong place. A server would answer 403 on the same URL, so the guard does the same:

export function permissionGuard(permission: Permission): CanActivateFn {
  return () => {
    if (inject(AccessService).can(permission)) return true;
    const router = inject(Router);
    return new RedirectCommand(router.parseUrl('/no-access'), { skipLocationChange: true });
  };
}
Enter fullscreen mode Exit fullscreen mode
// app.routes.ts
{
  path: 'billing',
  canActivate: [permissionGuard('billing.view')],
  runGuardsAndResolvers: 'always',
  loadChildren: () => import('./features/billing/billing.routes'),
},
{
  path: 'no-access',
  loadComponent: () => import('./features/no-access/no-access.page').then((m) => m.NoAccessPage),
},
Enter fullscreen mode Exit fullscreen mode

RedirectCommand (Angular 18+) is what lets a guard redirect with navigation options. With skipLocationChange: true the "no access" page renders but the address bar keeps saying /billing. Ignore runGuardsAndResolvers for now, it comes back in a minute.

Buttons

Just control flow:

@if (access.can('users.delete')) {
  <button class="btn-danger" (click)="confirmDelete(user)">Delete</button>
}
Enter fullscreen mode Exit fullscreen mode

On pages that everyone can see but only some roles can edit (the Team page, for example), I don't show a disabled form. I hide the buttons and add one line at the top: "Only Owners and Admins can invite or change members." A greyed-out button with no explanation just makes people ask why.

Preview as role

This started as a debugging tool for me and ended up being the thing people click first in the demo. A preview signal overrides the real role:

private readonly preview = signal<UserRole | null>(null);

readonly role = computed(() => this.preview() ?? this.auth.user()?.role ?? null);

previewAs(role: UserRole | null): Promise<boolean> {
  this.preview.set(role);
  return this.router.navigateByUrl(this.location.path(), { onSameUrlNavigation: 'reload' });
}
Enter fullscreen mode Exit fullscreen mode

Menus and buttons update by themselves because they read the same signal. The open page is the tricky bit: if you're on Billing and switch to Viewer, the guard has to run again. Navigating to the same URL with onSameUrlNavigation: 'reload' does that, but only if the route has runGuardsAndResolvers: 'always'. Without it the router decides nothing changed and you stay on a page you shouldn't see. That one took me longer to figure out than I'd like to admit.

The preview is only available with the mock API. With a real backend the role comes from the session and that's it.

The backend still decides

All of the above only hides things. Anyone with dev tools can call your API, so the server has to check the same permissions and answer 403.

To keep myself honest while building the UI, the mock API checks them too, with the same table:

export function mockForbidden(access: AccessService, permission: Permission): Observable<never> | null {
  return access.can(permission) ? null : mockError("Your role doesn't allow this action.", 403);
}

// in a mock API method
invite(request: InviteMemberRequest): Observable<Team> {
  const denied = mockForbidden(this.access, 'team.manage');
  if (denied) return denied;
  // … validation (422, 409) and the actual change
}
Enter fullscreen mode Exit fullscreen mode

So if I forget an @if somewhere, I get the same error toast the real server would produce, instead of finding out in production.

Limits

This works for "role X can do Y". It doesn't cover "members can edit only their own reports": that's a check on the data, not on the role, and it belongs in the component (and on the server). For a dashboard with four roles that's been fine. With dozens of custom roles you'd want the permissions to come from the backend instead of a hard-coded table, but the rest stays the same.


The code is from Providentia, a free Angular 22 + Tailwind 4 admin template I put together. It has all of the above plus a Team page, API keys and webhooks, and an OpenAPI file describing the backend it expects.

If you handle roles differently, especially the per-record kind of check, I'd like to hear how.

Top comments (6)

Collapse
 
adilbenmoussa profile image
Adil Ben Moussa •

Nice write-up, and Providentia looks really clean. The "Preview as role" switch shows the table idea better than any explanation.

Asking can('billing.view') instead of checking the role is the right habit. You mention custom roles should come from the backend, and in enterprise apps that is usually the first change request. The nice part is that can() and the Permission union stay, only the mapping moves.

How would you make sure the permissions are loaded before the synchronous guard runs on a hard refresh of /billing?

Collapse
 
rrstudioapps profile image
Roberto Russo •

Thanks! Glad the “Preview as role” switch gets the idea across.

Right now Providentia doesn’t get permissions from a server (yet!), so the problem isn’t there. The role is saved with the session in localStorage and read back at startup, and the permission table is in the code.

With a backend I’d load the permissions in the guard on the parent route (authGuard, in canMatch). canMatch accepts an Observable or a Promise, so it can wait for the server. And Angular runs the parent’s canMatch before the child’s canActivate, so permissionGuard can stay sync, the permissions are already loaded when it runs.

Something like this (loadPermissions doesn’t exist yet, it’s just the idea):

{
  path: '',
  canMatch: [authGuard],
  children: [
    { path: 'billing', canActivate: [permissionGuard('billing.view')] },
  ],
}

export const authGuard = () => {
  const auth = inject(AuthService);
  if (!auth.isAuthenticated()) return redirectToLogin;
  return auth.loadPermissions().pipe(map(() => true));
};
Enter fullscreen mode Exit fullscreen mode

That should cover the hard refresh case. But in the end the guard is just UX, the real check has to be on the backend anyway.

Collapse
 
adilbenmoussa profile image
Adil Ben Moussa •

Thanks Roberto, that is a clean answer. The parent's canMatch is the right place for the load: matching happens before any canActivate, so permissionGuard stays sync and simple. And agreed on your last line, the guard is UX and the backend decides.

One thing to watch: the router matches the routes again on every navigation, so authGuard runs on every click, not only on the hard refresh. loadPermissions() should cache its result (one request, then the stored value), or every navigation waits for the server.

What would you show when that request fails on a hard refresh: the login page, or an error page with a retry?

Thread Thread
 
rrstudioapps profile image
Roberto Russo • • Edited

Right, I'd put the cache in the Auth service. Keep the request in flight (a stored promise or shareReplay, either works) and the result in a signal, so only the first navigation pays for it. If the request fails I'd throw the cached promise away, otherwise retry does nothing. Same on login and logout.
For the failure case it depends on what failed. A 401 or 403 means the session is bad, so login with the return URL. A network error or a 500 is different: the user is still signed in, and sending them to login would just confuse them. Without the permission map the guard can't decide anything, so I'd show an error page with a retry button. That page can't sit behind the same guard, or you get a redirect loop.
You could also save the last map in localStorage and use it when the request fails. I'd skip that at first.

Thread Thread
 
adilbenmoussa profile image
Adil Ben Moussa •

Thanks Roberto, the split is clear: a 401 goes to login, a 500 stays signed in with a retry.

One small thing: with shareReplay(1) the next subscriber asks the server again after an error. Only the stored promise stays rejected and needs the reset.

Thread Thread
 
rrstudioapps profile image
Roberto Russo •

Thanks, you're right, I mixed those up!