← Back to Angular, page 10

angular-0185 · Hard senior

Design an admin panel with role-based access, many CRUD screens and audit needs. How do you structure routes, permissions, forms and tables so the codebase stays maintainable?

Split the app into lazy feature areas, derive route access and menu items from one permission model, enforce permissions in guards and in the UI through a directive, and always on the server. Reuse generic table, form and CRUD building blocks, keep API access in typed services, and log sensitive actions.

Full answer

Clarify first: how many roles and how fine grained the permissions are (roles only, or per resource and action), whether tenants or organisations exist, audit requirements, and the expected data sizes.

Structure:

  1. Feature areas. One lazy loaded route tree per area: students, teachers, fees, reports, settings. Each has its own routes, components and API service. Shared building blocks live in ui and data-access libraries. A shell component holds the layout, menu and header.
  2. Permission model. Use permissions as strings (students:read, students:write, fees:refund). Roles are sets of permissions that come from the server in the user profile after login. A PermissionService holds them in a signal, with can('students:write').
  3. One source of truth for access. Route definitions carry data: { permission: 'students:read' }. A canMatch guard reads it, so unauthorised users do not even download the lazy chunk, and redirects to a "forbidden" page. The menu is built from the same route data, so the menu and the routes cannot disagree.
  4. UI level control. A structural directive *appCan="'students:write'" shows or hides buttons and sections. Remember that this is user experience only. The API must check permissions on every request, because anyone can call it directly. Return 403 and handle it globally in an interceptor (message, not a crash).
  5. CRUD reuse. A generic DataTable component takes column definitions and a data source (server side paging, sorting, filters in the URL). A form builder component creates typed reactive forms from field definitions for simple screens, and complex screens get custom forms. Keep a small set of patterns, not a code generator for everything.
  6. API layer. One typed service per resource, using httpResource or HttpClient. Central error mapping (validation errors from the server mapped to form controls).
  7. Safety nets: confirm dialogs for destructive actions, optimistic updates only where rollback is easy, canDeactivate guard for unsaved forms, and idempotent endpoints for retries.
  8. Audit and observability: the server records who did what. The client sends a correlation id, and logs errors.
  9. Testing: unit tests for the permission service and guards, component tests for the table and forms, and e2e tests for one flow per role.

State the trade-off: fine grained permissions give flexibility, but need careful naming and tests. Start with the simplest model that meets the rules, and keep the permission check in one place so the model can grow.

typescript
import { Directive, Injectable, TemplateRef, ViewContainerRef, computed, effect, inject, input, signal } from '@angular/core';
import { CanMatchFn, Route, Router } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class PermissionService {
  private readonly granted = signal<ReadonlySet<string>>(new Set());

  load(permissions: string[]): void {
    this.granted.set(new Set(permissions));
  }

  can(permission: string): boolean {
    return this.granted().has(permission);
  }

  readonly count = computed(() => this.granted().size);
}

export const permissionMatch: CanMatchFn = (route: Route) => {
  const required = route.data?.['permission'] as string | undefined;
  const permissions = inject(PermissionService);
  return !required || permissions.can(required) ? true : inject(Router).parseUrl('/forbidden');
};

@Directive({ selector: '[appCan]' })
export class CanDirective {
  readonly appCan = input.required<string>();
  private readonly permissions = inject(PermissionService);
  private readonly template = inject(TemplateRef<unknown>);
  private readonly container = inject(ViewContainerRef);

  constructor() {
    effect(() => {
      this.container.clear();
      if (this.permissions.can(this.appCan())) {
        this.container.createEmbeddedView(this.template);
      }
    });
  }
}

// { path: 'fees', canMatch: [permissionMatch], data: { permission: 'fees:read' }, loadChildren: ... }
// <button *appCan="'students:write'">Add student</button>

Angular 20.3, type-checked. A Karma test checks the guard result for an allowed and a denied permission and the directive output. The pieces were not assembled into a full admin application.

Key points

  • Lazy feature areas with shared `ui` and `data-access` building blocks.
  • String permissions from the server, held in a signal service. Routes and menu read the same data, and `canMatch` blocks unauthorised areas.
  • A permission directive improves UX, but the server enforces access.
  • Reusable table and form patterns, typed API services and a global error interceptor.

Common mistakes

  • Relying on hidden buttons for security.
  • Different permission checks scattered in many components.
  • Generating every screen from a generic builder, even complex ones.

Follow-ups

  • How do you handle a permission change while the user is logged in?
  • Why `canMatch` and not only `canActivate`?
  • How would you keep the menu in sync with routes?

Tips

  • State clearly that the server is the real authority.
  • Use one route data field for guard and menu.
  • Mention audit and testing per role.

Evaluation rubric

  • Designs routing, permissions and reuse coherently.
  • Separates UX control from security.
  • Covers safety, audit and tests.