← Back to Angular, page 10

angular-0186 · Hard senior

How would you implement multi-tenant theming (different brand colours and logos per school) in an Angular app without rebuilding for each tenant?

Define the design with CSS custom properties (design tokens) in the stylesheet, load each tenant's token values at run time from configuration, and write them on the document root. Components only use var(--brand-primary). Validate contrast of the supplied colours, and fall back to safe defaults when a value is missing or fails.

Full answer

The key idea is to separate the design decision (what colours exist) from the value (which brand colour a school chose). Build once, theme at run time.

  1. Tokens as CSS custom properties. In global styles define defaults: :root { --brand-primary: #1d4ed8; --brand-on-primary: #ffffff; --surface: #ffffff; }. Components use background: var(--brand-primary) and never a hard coded colour. CSS variables cross component style encapsulation, and can be changed at run time without recompiling. Angular Material's system tokens work in the same way.
  2. Tenant configuration. Resolve the tenant from the host name (greenfield.school.app), a path segment, or the login. Load the theme from the backend or a theme.json before the app renders (in provideAppInitializer), to avoid a flash of the default theme. Cache it, and keep a default when the request fails.
  3. A ThemeService with a signal for the active theme. An effect writes each token to document.documentElement.style.setProperty('--brand-primary', value). For server rendering, set the same values in the server response (or on a wrapper element) so the first paint is correct, and use the injected DOCUMENT, not the global document.
  4. Assets: logo and favicon URLs come from the theme. Use NgOptimizedImage for the logo.
  5. Accessibility and safety: tenants choose colours, so check them. Compute the WCAG contrast ratio between text and background, require at least 4.5 to 1 for normal text, and reject or adjust a palette that fails. Validate that values are hex colours before writing them to the style, because they are user supplied data (do not accept arbitrary CSS).
  6. Dark mode: a second set of tokens under [data-theme="dark"] or prefers-color-scheme. The theme service sets the attribute.
  7. Testing: unit test the contrast function and the service (the variable is written), and a visual regression test for two sample tenants.

Alternatives and trade-offs: separate builds per tenant (simple CSS, but many deployments), Sass maps compiled for a fixed list of tenants (fast, but needs a rebuild per new tenant), and run time tokens (flexible, no rebuild). The run time token approach is the usual choice for many tenants.

For layout differences, not just colours, use feature flags or a configuration object, and keep one component set.

typescript
import { DOCUMENT } from '@angular/common';
import { Injectable, effect, inject, signal } from '@angular/core';

export interface Theme {
  primary: string;
  onPrimary: string;
}

const HEX = /^#[0-9a-fA-F]{6}$/;

function luminance(hex: string): number {
  const channel = (i: number) => {
    const c = parseInt(hex.slice(1 + i * 2, 3 + i * 2), 16) / 255;
    return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
  };
  return 0.2126 * channel(0) + 0.7152 * channel(1) + 0.0722 * channel(2);
}

export function contrastRatio(a: string, b: string): number {
  const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x);
  return (light + 0.05) / (dark + 0.05);
}

export const DEFAULT_THEME: Theme = { primary: '#1d4ed8', onPrimary: '#ffffff' };

@Injectable({ providedIn: 'root' })
export class ThemeService {
  private readonly doc = inject(DOCUMENT);
  readonly theme = signal<Theme>(DEFAULT_THEME);

  constructor() {
    effect(() => {
      const t = this.theme();
      this.doc.documentElement.style.setProperty('--brand-primary', t.primary);
      this.doc.documentElement.style.setProperty('--brand-on-primary', t.onPrimary);
    });
  }

  apply(candidate: Theme): boolean {
    const valid = HEX.test(candidate.primary) && HEX.test(candidate.onPrimary);
    if (!valid || contrastRatio(candidate.primary, candidate.onPrimary) < 4.5) {
      return false; // keep the current theme
    }
    this.theme.set(candidate);
    return true;
  }
}

Angular 20.3, type-checked. A Karma test applies a theme, reads the CSS variable from the root element, rejects an invalid colour, and checks contrast ratios for black on white (21) and a light grey on white (below 4.5).

Key points

  • Use design tokens as CSS custom properties. Components use `var(--token)`.
  • Load tenant values at start-up, write them on the root through a signal driven service.
  • Validate colours (format and WCAG contrast) because tenants supply them.
  • Run time theming avoids per-tenant builds. Provide defaults and handle server rendering.

Common mistakes

  • Hard coding colours in component styles.
  • Accepting arbitrary CSS strings from tenant configuration.
  • Showing the default theme first and then flashing to the tenant theme.

Follow-ups

  • How would you avoid the flash of the default theme with SSR?
  • How do you check colour contrast programmatically?
  • When would separate builds be better?

Tips

  • Start with the token idea, then the loading and validation steps.
  • Mention the contrast rule as an accessibility duty.
  • Compare with the build-time options.

Evaluation rubric

  • Uses CSS variables and runtime configuration correctly.
  • Validates tenant input and contrast.
  • Discusses SSR, defaults and trade-offs.