How to implement dark mode in an Angular application
Dark mode is more than a colour inversion. A reliable implementation gives people control over readability, glare and visual comfort while preserving interface hierarchy. It should respect operating-system preferences and stay predictable across visits and devices. Angular suits the task because signals, services and CSS custom properties keep the theme consistent without duplicating state in components.
The local context matters. A commuter on a Melbourne tram or Sydney train may read a phone in a crowded carriage, while a customer in Brisbane may open the same service in bright daylight or late at night. Daylight saving changes evening light in New South Wales, Victoria, South Australia and Tasmania, but not Queensland or Western Australia. For Australian retail and service products, the theme control should work on mobile, desktop and slower regional connections.
A dependable theme has three layers: the user's chosen preference, the operating-system fallback and a resolved theme that components render. This separation prevents an explicit light selection from being overwritten by a dark operating system, while still allowing “system” to follow a change made in macOS, Windows or Android settings. The implementation should survive server-side rendering, hydration and blocked browser storage. The result should feel like one coherent interface, with readable text, visible controls and predictable contrast rather than a set of inverted component styles.
Start with a theme contract
Begin with a clear contract. Expose three choices—system, light and dark—and store the selected preference as a named type rather than a loose string. “System” should remain the default for a first visit, since it respects the environment without asking for an unnecessary decision. A user who chooses an explicit theme expects it to win until they change the setting again. Keep this policy in one service so navigation, dialogs and background jobs cannot drift into different visual states.
Define colour roles before choosing exact shades. Components should consume semantic tokens such as --surface, --surface-raised, --text, --text-muted, --border and --accent, rather than hard-coded greys. Test hover, focus, disabled and error states in every theme. For Australian public-sector and regulated services, the Australian Accessibility Standards matter; WCAG 2.2 AA is a useful target. Normal text requires 4.5:1 contrast, while large text and meaningful interface graphics require 3:1.
Treat the preference as a usability setting, not a tracking record. If it stays in browser storage, the application does not need to reveal the visitor's appearance choices to a server. If a signed-in user syncs the choice across devices, then it becomes account data and may fall within the Privacy Act 1988 and Australian Privacy Principles. Document the purpose, limit collection and obtain appropriate consent where required. Local storage can still be cleared, shared across tabs or rejected, so the product must behave correctly when it is unavailable.
Prepare the application for theme changes
Modern Angular applications benefit from a single injectable service. The service owns the preference and resolved-theme signals, reads the operating-system setting with matchMedia, and updates the root document when the choice changes. Components should bind to those signals instead of reading localStorage or querying the media feature themselves. This keeps the state model testable and allows an Angular Material component, a custom component and a third-party widget to receive the same theme.
Server-side rendering deserves particular attention. Guard window and localStorage with a browser-only check, but watch for a flash when the first painted page is light and the stored preference is dark. A small script in the document head can set data-theme before the main styles render; under a strict Content Security Policy, give it a nonce or hash. When an SSR application already has a server-side session, a narrowly scoped theme cookie lets the server render the correct attribute.
Storage is an unreliable dependency. Safari in private browsing, embedded web views and hardened enterprise policies can deny access, while a quota error can occur after a user has filled the origin's allocation. Wrap every read and write in error handling and keep an in-memory preference as the working fallback. Decide whether a stored value for a previous application version should be migrated or discarded; changing the key is often safer than interpreting an obsolete value. The UI should still respond immediately even if persistence fails.
Build a reactive theme service
A signal-based service gives the application one source of truth. The following Angular example supports all three choices, reacts when the operating system changes and safely tolerates storage failures:
import { DOCUMENT, isPlatformBrowser, PLATFORM_ID } from '@angular/common';
import {
afterNextRender, computed, DestroyRef, effect, inject,
Injectable, signal
} from '@angular/core';
export type ThemePreference = 'system' | 'light' | 'dark';
type ResolvedTheme = 'light' | 'dark';
@Injectable({ providedIn: 'root' })
export class ThemeService {
private readonly document = inject(DOCUMENT);
private readonly platformId = inject(PLATFORM_ID);
private readonly destroyRef = inject(DestroyRef);
private readonly window = this.document.defaultView;
private readonly media = this.window?.matchMedia?.('(prefers-color-scheme: dark)');
private readonly ready = signal(false);
private readonly systemDark = signal(false);
readonly preference = signal<ThemePreference>('system');
readonly resolvedTheme = computed<ResolvedTheme>(() => {
const choice = this.preference();
if (choice !== 'system') return choice;
return this.systemDark() ? 'dark' : 'light';
});
private readonly onSystemChange = (event: MediaQueryListEvent) => {
this.systemDark.set(event.matches);
};
constructor() {
afterNextRender(() => {
this.systemDark.set(this.media?.matches ?? false);
const saved = this.readPreference();
if (saved) this.preference.set(saved);
this.ready.set(true);
this.media?.addEventListener('change', this.onSystemChange);
this.destroyRef.onDestroy(() =>
this.media?.removeEventListener('change', this.onSystemChange)
);
});
effect(() => {
if (!isPlatformBrowser(this.platformId) || !this.ready()) return;
const theme = this.resolvedTheme();
this.document.documentElement.dataset['theme'] = theme;
this.document.documentElement.style.colorScheme = theme;
this.savePreference(this.preference());
});
}
setPreference(value: ThemePreference): void {
this.preference.set(value);
}
private readPreference(): ThemePreference | null {
try {
const value = this.window?.localStorage.getItem('app-theme');
return value === 'system' || value === 'light' || value === 'dark'
? value : null;
} catch {
return null;
}
}
private savePreference(value: ThemePreference): void {
try {
this.window?.localStorage.setItem('app-theme', value);
} catch {
// The in-memory preference still works when storage is unavailable.
}
}
}
The preference signal records intent; resolvedTheme records what appears. The effect applies the resolved value to the root element, so CSS can select the matching token set. matchMedia is used rather than a one-time media query because users can change their desktop theme while the application remains open. The listener is removed when the service is destroyed. During SSR, afterNextRender keeps browser-only work on the client, and the readiness flag prevents the initial effect from overwriting a stored choice.
Expose the service through a three-option radio group rather than cycling blindly. A radio group gives each option a stable label, supports keyboard navigation and lets assistive technology announce the selection. Announce changes politely if the page repaints, but do not move focus after selection. Preserve focus indicators in both palettes, and use an icon plus visible text where possible. The control should call setPreference, leaving persistence inside the service.
Patterns and failure points for theme styling
Global custom properties are the cleanest styling layer. Define every semantic token in the document root, then let component styles consume those variables. The root color-scheme declaration supports the system result before JavaScript runs, while an explicit data-theme attribute takes precedence. Keep component-specific variants sparse; they should adjust imagery or spacing rather than introduce a parallel palette.
:root {
color-scheme: light dark;
--surface: light-dark(#ffffff, #111827);
--surface-raised: light-dark(#f3f4f6, #1f2937);
--text: light-dark(#111827, #f9fafb);
--text-muted: light-dark(#4b5563, #d1d5db);
--border: light-dark(#9ca3af, #6b7280);
--accent: light-dark(#1d4ed8, #60a5fa);
}
:root[data-theme='light'] {
color-scheme: light;
}
:root[data-theme='dark'] {
color-scheme: dark;
}
The light-dark() function keeps each token's two values together and follows the selected colour scheme. If the browser matrix includes older engines, compile equivalent token overrides instead. Components can use background: var(--surface) and color: var(--text) without knowing which theme is active. This avoids rebuilding component trees when the setting changes: one root attribute updates the cascade across the page.
Reliable patterns to keep
- Keep palette values in semantic tokens rather than component styles.
- Store one preference and derive the visible theme from it.
- Offer system, light and dark choices with clear selected states.
- Pair native colour-scheme support with accessible focus indicators.
- Test system changes, explicit choices and missing storage separately.
Common failure points to avoid
- Hard-coding colours in templates that bypass the token palette.
- Mechanically inverting every hex value, including brand and status colours.
- Accepting low-contrast muted text, borders or disabled control states.
- Assuming localStorage is always available or always contains a valid value.
- Overriding an explicit choice whenever the operating-system theme changes.
Images, charts and maps need separate attention because many assets carry baked-in colours that a CSS variable cannot repair. For canvas, read the resolved token values and redraw when resolvedTheme changes; for SVG, prefer currentColor and CSS classes. Third-party embeds are separate accessibility cases because an iframe does not inherit the host page's custom properties.
Test behaviour across themes and devices
Test the behaviour at several levels. Service tests should cover the default system preference, an explicit saved choice, a change to the operating-system setting and a denied storage operation. Component tests should verify that the radio group reflects the service and that keyboard users can change it. End-to-end tests can emulate both colour schemes and assert the root attribute, persisted value and visible token changes without relying on a particular screenshot shade.
Run a visual pass with real content. Check body text, muted labels, focus rings, hover and disabled states, validation messages, price tables and Australian date formats. Emulate forced-colours mode: an operating-system accessibility setting may replace the palette entirely. Images and third-party content need light, dark and high-contrast variants. A practical code review guide can prompt reviewers to check these branches alongside unit tests.
Watch for the flash of the wrong theme on a cold load, including direct visits and back-forward navigation. Test on a mid-range Android phone used on mobile data, an iPhone in landscape and a desktop browser at 200% zoom. Then use Lighthouse or an equivalent accessibility scanner, followed by manual keyboard and screen-reader checks. Store baseline screenshots for both themes and review them when design tokens change; otherwise a subtle contrast regression can survive a passing test suite.
Choose the three-option control, wire it to the theme service, and verify the complete light and dark paths before shipping. Keep one preference model, one token palette and one observable root attribute, so future theme changes remain predictable rather than becoming another round of component-by-component fixes.