Dev.to WebDev 🛠 Dev 👁 0 📖 5 min read

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 stil

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);
}

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);
  }
}

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);
}

and the sidebar is one line:

protected readonly sections = computed(() => allowedNavigation((p) => this.access.can(p)));

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 });
  };
}
// 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),
},

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>
}

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' });
}

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
}

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.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.