Full answer
Feature flags let you ship code switched off, release it gradually, run experiments, and turn a feature off quickly if it causes trouble. In Angular, three pieces cover most needs.
- Flag service.
FeatureFlagServiceholds the flags in a signal (Record<string, boolean>), and exposesisEnabled(name). Flags are loaded before the first render withprovideAppInitializerfrom your backend or a flag provider (LaunchDarkly, Unleash, a JSON file). Use a timeout and safe defaults: if loading fails, flags are off (or a stable cached copy is used), and the app still starts. Reading the signal inside a template orcomputedmakes the UI update when flags change. - Directive.
*appFeature="'newDashboard'"renders content only when the flag is on, and supports anelsetemplate. This keeps templates tidy and avoids@if (flags.isEnabled('x'))everywhere. - Route guard.
canMatch: [featureGuard('newDashboard')]makes a route "not exist" when the flag is off, so the next matching route (the old page) is used, and the lazy chunk of the new feature is never downloaded.canMatchis better thancanActivatefor flags, because it can fall through to an alternative route.
Rollout and targeting: the flag decision can depend on the user, the tenant or a percentage. Evaluate on the server or with a provider SDK so users do not see their own flag rules, and so the same user always gets the same result (sticky bucketing).
Risks and rules:
- Flags are technical debt. Every flag needs an owner, a purpose and a removal date. Remove the flag and the old code once the feature is fully released.
- Combinations: n flags give 2^n states. Keep flags independent and few, and test the on and off cases of each one.
- Never use flags for security. Client side flags are visible and can be changed in the browser, so the server must enforce access.
- Avoid flicker: load flags before render, or show a skeleton.
- Server rendering and caching: flags that vary per user must not be cached in shared HTML.
- Observability: log which flags were active when an error happened.
Testing: provide a fake FeatureFlagService or set flags in the test, and assert both branches.
import { Directive, Injectable, TemplateRef, ViewContainerRef, effect, inject, input, signal } from '@angular/core';
import { CanMatchFn } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class FeatureFlagService {
private readonly flags = signal<Record<string, boolean>>({});
isEnabled(name: string): boolean {
return this.flags()[name] === true; // unknown flags are off
}
async load(fetchFlags: () => Promise<Record<string, boolean>>, timeoutMs = 1500): Promise<void> {
try {
const timeout = new Promise<never>((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs));
this.flags.set(await Promise.race([fetchFlags(), timeout]));
} catch {
// keep the defaults: the app must still start
}
}
}
@Directive({ selector: '[appFeature]' })
export class FeatureDirective {
readonly appFeature = input.required<string>();
private readonly flags = inject(FeatureFlagService);
private readonly template = inject(TemplateRef<unknown>);
private readonly container = inject(ViewContainerRef);
constructor() {
effect(() => {
this.container.clear();
if (this.flags.isEnabled(this.appFeature())) {
this.container.createEmbeddedView(this.template);
}
});
}
}
export const featureGuard =
(name: string): CanMatchFn =>
() =>
inject(FeatureFlagService).isEnabled(name);
// provideAppInitializer(() => inject(FeatureFlagService).load(() => fetch('/api/flags').then((r) => r.json())))
// { path: 'dashboard', canMatch: [featureGuard('newDashboard')], loadComponent: () => import('./new-dashboard') }
// { path: 'dashboard', loadComponent: () => import('./old-dashboard') }Angular 20.3, strict template check passes. A Karma test checks that the directive shows and hides content when the flag changes, that `canMatch` returns true or false, and that a failed load keeps the defaults.
Key points
- A signal-based `FeatureFlagService` loaded in `provideAppInitializer`, with timeout and safe defaults.
- A structural directive for templates and a `canMatch` guard for routes (falls through and avoids downloading disabled code).
- Flags are temporary debt. Name, own and remove them. Test on and off states.
- Flags are not security. The server enforces access.
Common mistakes
- Letting a failed flag request block app start.
- Using `canActivate` for flags and leaving the lazy chunk downloadable.
- Never removing old flags.
Follow-ups
- How do you make a percentage rollout sticky per user?
- Why is `canMatch` a good fit for flags?
- How do you test code that depends on a flag?
Tips
- Show all three pieces briefly.
- Say that flags are debt and need a removal plan.
- Mention security and caching limits.
Evaluation rubric
- Implements service, directive and guard correctly.
- Handles start-up failure and rollout concerns.
- States risks and test strategy.