Questions 181–195 of 195 · 0 of 15 on this page marked learned
181.angular-0181Mediummid
How does the OAuth 2.0 / OIDC authorization code flow with PKCE work in a single page Angular app, and how do a route guard and an HTTP interceptor use it?
The app redirects the browser to the identity provider with a code challenge (the hash of a secret verifier). After login the provider redirects back with a code, and the app exchanges the code plus the verifier for tokens. A guard sends users without a token to login and remembers the return URL, and an interceptor adds the access token to API calls only.
Full answer
A single page app cannot keep a client secret, so it uses the authorization code flow with PKCE (Proof Key for Code Exchange). This is the recommended flow for browser apps. The older implicit flow, which returned tokens in the URL, is no longer recommended.
The steps:
The app creates a random code_verifier and a state value, and stores them (session storage). It computes code_challenge = base64url(SHA-256(code_verifier)).
It redirects the browser to the identity provider's /authorize URL with response_type=code, client_id, redirect_uri, scope=openid profile, state, code_challenge and code_challenge_method=S256.
The user logs in at the provider (not in your app), and the provider redirects back to your redirect_uri with code and state.
The app checks that state matches (protection against forged callbacks), then calls the /token endpoint with grant_type=authorization_code, the code and the original code_verifier. The provider hashes the verifier and compares it with the challenge from step 2. An attacker who steals the code cannot use it without the verifier.
The response has an access token (to call APIs), an ID token (who the user is, OIDC), and often a refresh token. The app keeps the access token in memory when possible, and refreshes it before it expires.
In Angular:
Functional guard: canActivate checks auth.isAuthenticated(). If false, it saves the wanted URL and returns a UrlTree for /login. After login, navigate to the saved URL.
Interceptor: adds Authorization: Bearer <token> only for requests to your API origin, never to third party URLs. On a 401, it can refresh once and retry.
Callback route: reads code and state, calls the token exchange, then navigates on.
Security points: guards only improve the user experience, because the server must always check the token. Do not store tokens in localStorage if you can avoid it, since any XSS can read them. Check iss, aud and expiry on the server. In production, use a maintained library (angular-auth-oidc-client, oidc-client-ts, or a provider SDK) and not hand-written code. Another option is a backend for frontend (BFF) that keeps tokens in HTTP-only cookies.
Angular 20.3, type-checked. A Karma test checks the PKCE challenge against the example from RFC 7636, the guard redirect with the saved return URL, and that the interceptor adds the header only for the API origin. The redirect to a real identity provider and the token exchange were not run.
Key points
Use authorization code flow with PKCE for browser apps. The verifier never travels in the redirect.
Check `state` on return, then exchange `code` plus verifier for tokens.
Guard redirects with a return URL. Interceptor adds the token to your API only.
The server must validate tokens. Prefer a maintained library or a BFF.
Common mistakes
Adding the bearer token to every outgoing request, including third party ones.
Skipping the `state` check.
Treating the guard as security instead of user experience.
Follow-ups
Why is PKCE needed when there is no client secret?
Where would you keep the access token, and what are the risks?
How would you refresh a token without making several refresh calls at once?
Tips
Walk through the five steps in order.
Explain what PKCE protects against in one sentence.
Mention libraries and the BFF option.
Evaluation rubric
Explains the code flow with PKCE correctly.
Implements guard and interceptor safely.
Notes the security limits of client-side checks.
182.angular-0182Mediummid
What does DomSanitizer.bypassSecurityTrustHtml do, why is it risky, and what are the safe patterns when you really need it?
Angular sanitizes values bound to innerHTML, src, href and style, removing scripts, event handler attributes and unsafe URLs. bypassSecurityTrustHtml (and the Url, ResourceUrl, Style and Script versions) tells Angular to skip that for one value. If the value contains user data, it opens a cross-site scripting hole. Use it only on values you built yourself, validated against an allowlist, or cleaned by a sanitizer library.
Full answer
Angular treats every template value as untrusted. Interpolation ({{ text }}) escapes HTML, so markup shows as text. Bindings that go into dangerous places, such as [innerHTML], [src], [href] and [style], are sanitized: scripts are removed, event attributes such as onmouseover are dropped, and javascript: URLs are rewritten to unsafe:.... In development, the console warns "sanitizing HTML stripped some content".
Sometimes this blocks valid content: an embedded video iframe, trusted CMS HTML with inline styles, a blob: or tel: link. DomSanitizer offers bypassSecurityTrustHtml, bypassSecurityTrustStyle, bypassSecurityTrustScript, bypassSecurityTrustUrl and bypassSecurityTrustResourceUrl. The returned object is a marker: Angular puts the value into the DOM as it is.
Why it is dangerous: the name says "trust", and you take over the responsibility. If a part of the value comes from a user, a database field or an API, an attacker can store <img src=x onerror=stealToken()> and run script in every visitor's browser (stored XSS). That script can read tokens, send requests as the user, and change the page.
Safe patterns:
Prefer no bypass. [innerHTML] with the default sanitizer is already safe for most rich text.
Build, do not accept. For a video, accept only an id, validate it with a regular expression (/^[\w-]{11}$/), build the URL yourself from a fixed origin, and only then call bypassSecurityTrustResourceUrl.
Sanitize with a dedicated library such as DOMPurify (with a strict allowlist of tags and attributes) before bypassing, for HTML that must keep more than Angular allows.
Isolate: use a sandboxed iframe (sandbox attribute) for untrusted documents.
Defence in depth: a Content Security Policy that blocks inline scripts, and Trusted Types. Angular supports Trusted Types, which makes dangerous sinks accept only trusted objects.
Keep the bypass call in one small, reviewed service or pipe, never inline in components, so it is easy to search and audit. Add a lint rule or a code review check for bypassSecurityTrust.
Also never use ElementRef.nativeElement.innerHTML or document.write with user data. They skip Angular's protection completely.
typescript
import { Component, inject } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeResourceUrl } from '@angular/platform-browser';
export const hostile = `<b onmouseover="1">bold</b><script>1</script><a href="javascript:void(0)">link</a>`;
@Component({
selector: 'app-html-demo',
template: `
<div id="sanitized" [innerHTML]="hostile"></div>
<div id="bypassed" [innerHTML]="trusted"></div>
`,
})
export class HtmlDemoComponent {
private readonly sanitizer = inject(DomSanitizer);
readonly hostile = hostile;
// Risky: only acceptable for HTML that you wrote yourself.
readonly trusted: SafeHtml = this.sanitizer.bypassSecurityTrustHtml(hostile);
}
// Safer pattern: accept an id, validate it, build the URL, then trust the result.
export function videoEmbedUrl(sanitizer: DomSanitizer, id: string): SafeResourceUrl | null {
if (!/^[\w-]{11}$/.test(id)) {
return null;
}
return sanitizer.bypassSecurityTrustResourceUrl(`https://www.youtube-nocookie.com/embed/${id}`);
}
Angular 20.3, strict template check passes. A Karma test renders the same hostile HTML through the default sanitizer and through the bypass, and checks that `onmouseover` and the script tag are removed in the first and kept in the second. No hostile code was executed. The embed helper was checked with valid and invalid ids.
Key points
Angular sanitizes innerHTML, URL and style bindings. Bypass methods switch this off for one value.
Bypassing with user-influenced data creates stored or reflected XSS.
Safe patterns: avoid bypass, build from validated parts, sanitize with an allowlist library, isolate with sandbox, use CSP and Trusted Types.
Keep bypass calls in one audited place.
Common mistakes
Calling `bypassSecurityTrustHtml(userInput)` to "make the warning go away".
Setting `nativeElement.innerHTML` directly.
Accepting a full URL from users for an iframe and bypassing it.
Follow-ups
What does Angular do to a `javascript:` link by default?
How would you allow YouTube embeds safely?
What does a Content Security Policy add?
Tips
Show one attack string and what the sanitizer does to it.
Give the "validate, build, then trust" rule.
Mention CSP and Trusted Types as extra layers.
Evaluation rubric
Explains default sanitization and the bypass methods.
Describes the XSS risk precisely.
Gives several practical safe patterns.
183.angular-0183Mediummid
How do you test the accessibility of an Angular app? What can automated tools such as axe find, and what must you check by hand?
Use several layers: template lint rules while coding, axe-core checks in component and e2e tests, Lighthouse in CI, and manual checks with keyboard only and a screen reader. Automated tools find missing labels, alt text, bad ARIA and some contrast problems, but cannot judge whether the experience makes sense.
Full answer
Accessibility (a11y) means people who use keyboards, screen readers, zoom or voice control can use the app. WCAG is the standard, and level AA is the usual target. Testing needs several layers, because no single tool finds everything.
Lint while you write. angular-eslint has template accessibility rules, such as alt-text, label-has-associated-control, click-events-have-key-events, interactive-supports-focus and valid-aria. They catch mistakes in the editor and in pull requests.
Automated checks in tests. axe-core scans a DOM and returns violations with rule id, impact and the failing element. Run it in unit or component tests on the rendered fixture (axe.run(fixture.nativeElement), or jest-axe and vitest-axe wrappers), and in e2e tests on whole pages (@axe-core/playwright). Fail the test when there are violations, and keep a small, documented list of exceptions.
Lighthouse or Pa11y in CI for page level reports and trends.
Manual checks, which matter most:
Keyboard only: can you reach and use every control with Tab, Shift+Tab, Enter, Space and arrow keys? Is the focus order logical, and is the focus always visible? After opening a dialog, does focus move into it and return afterwards?
Screen reader: test with NVDA or VoiceOver. Are names, roles, states and error messages announced? Do route changes announce the new page (focus the heading or use LiveAnnouncer)?
Zoom to 200 percent and a narrow window: nothing is cut off. Check colour contrast and do not use colour as the only signal.
Reduced motion and text spacing settings.
What automated tests find well: missing form labels, missing alt text, duplicate ids, invalid ARIA attributes, empty buttons and links, document language, and many contrast failures. What they cannot judge: whether a label is meaningful, whether the reading order makes sense, whether a custom widget really works with a keyboard, and whether the page is understandable. Treat a green axe run as "no known basic faults", not as "accessible".
Angular helps with @angular/cdk/a11y (FocusTrap, FocusMonitor, LiveAnnouncer, ListKeyManager) and Angular Material, which follows ARIA patterns. Still test your own composition.
Process: define a checklist in the definition of done, test new components with axe in the same pull request, and run a manual audit before large releases.
Angular 20.3 with axe-core. A Karma test runs axe on a form with missing labels and a missing image alt, and on a fixed version. The violations found were button-name, image-alt and label for the bad form, and none for the fixed one. Screen reader and keyboard checks were not run.
Key points
Layers: lint rules, axe in tests, Lighthouse in CI, and manual keyboard and screen reader checks.
Automated tools find mechanical problems (labels, alt text, ARIA validity, some contrast). They cannot judge meaning or flow.
Check focus order, visible focus, dialog focus handling, and route change announcements by hand.
CDK a11y and Material help, but your own composition still needs testing.
Common mistakes
Treating a clean axe report as proof that the app is accessible.
Testing only with a mouse.
Adding ARIA attributes that contradict native semantics instead of using the right element.
Follow-ups
How do you announce a route change to a screen reader?
Why is a native `button` better than a `div` with a click handler?
How would you add axe checks to the existing test suite?
Tips
List the four layers.
Give examples of what each layer cannot find.
Mention the keyboard test first. It shows real experience.
Evaluation rubric
Names the layers and tools accurately.
Knows the limits of automation.
Includes concrete manual checks.
184.angular-0184Hardsenior
Design the front end of a dashboard with many widgets (charts, tables, KPIs) that load data independently. How do you structure the Angular app?
Treat each widget as a self-contained component with its own data resource, loading, error and empty states, so one failure does not break the page. Load above-the-fold widgets first and the rest with @defer, share data through a small service layer with caching, and keep layout configuration separate from widget code.
Full answer
Start by clarifying requirements: how many widgets, how fresh the data must be (real time or every minute), who configures the layout, what devices, and what the slowest backend call is. Then explain the design in layers.
Layout. A grid component renders widgets from a configuration array ({ id, type, size, position }). Widgets are looked up by type in a registry (a map from type to component), and created with NgComponentOutlet or @switch. This allows user-defined layouts, saved per user, without changing widget code.
Widget contract. Every widget is a standalone component with a small input interface (config, filters) and the same states: loading (skeleton), error (message and retry button), empty, and data. A shared wrapper component (widget-card) gives the same frame, title, refresh button and error handling.
Data access. Each widget owns its request using resource() or httpResource() keyed by the global filters (date range, class). When filters change, only affected widgets reload, and in-flight requests are cancelled. A thin data service per domain (MarksApi, AttendanceApi) hides URLs, mapping and caching. For shared data (the same query in two widgets), add a short-lived cache with request deduplication, or use a batched endpoint.
Loading strategy. Render the shell first. Load above-the-fold widgets right away, and everything else lazily with @defer (on viewport), with a placeholder of the same size so the layout does not jump. Charting libraries are large, so import them inside the deferred widget only.
Failure isolation. Errors are handled inside the widget. A failed chart shows "Could not load. Retry" while others stay usable. Add timeouts and limited retries with backoff.
Freshness. Polling with timer and switchMap (pause when the tab is hidden), or a WebSocket or server sent events for live widgets, with one shared connection in a service and share() to fan out.
State. Global filters live in a signal store or a service. Widget state stays local. Put URL state (filters, tab) into query params so a link can be shared.
Performance. OnPush and signals everywhere, track in lists, virtual scroll for big tables, canvas based charts for large series, and a performance budget. Measure with the profiler.
Quality. Accessibility (charts need text alternatives or a data table), tests for the wrapper and for each widget's states, and error and timing logging per widget.
Name the trade-offs: independent requests are simple and isolated, but many requests; a combined endpoint is efficient, but couples widgets. A good answer mentions both and picks one for the stated numbers.
typescript
import { Component, Type, input } from '@angular/core';
import { NgComponentOutlet } from '@angular/common';
export interface WidgetConfig {
id: string;
type: 'marks-chart' | 'attendance-kpi';
columns: number;
}
@Component({ selector: 'app-marks-chart', template: `Marks chart` })
export class MarksChartComponent {}
@Component({ selector: 'app-attendance-kpi', template: `Attendance KPI` })
export class AttendanceKpiComponent {}
// The registry maps a type from saved configuration to a component.
export const widgetRegistry: Record<WidgetConfig['type'], Type<unknown>> = {
'marks-chart': MarksChartComponent,
'attendance-kpi': AttendanceKpiComponent,
};
@Component({
selector: 'app-dashboard-grid',
imports: [NgComponentOutlet],
template: `
@for (w of widgets(); track w.id) {
<section [style.grid-column]="'span ' + w.columns" [attr.aria-label]="w.type">
<ng-container *ngComponentOutlet="registry[w.type]" />
</section>
}
`,
styles: [`:host { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1rem; }`],
})
export class DashboardGridComponent {
readonly widgets = input.required<WidgetConfig[]>();
readonly registry = widgetRegistry;
}
Angular 20.3, strict template check passes. This is a design answer. The code shows the widget wrapper contract and the type registry, and was type-checked, but not run as a whole dashboard.
Key points
Widgets are self-contained components with a shared card wrapper and the same four states.
A layout config plus a type registry allows user-defined dashboards.
Each widget loads its own data (`resource`), so failures are isolated and requests cancel on filter change.
Use `@defer` for below-the-fold widgets, placeholders to avoid layout jumps, and shared services for caching and live data.
Common mistakes
One big component that loads everything, so one slow call blocks the page.
Starting with technology and not with requirements.
Charts without text alternatives.
Follow-ups
How would you let users add and reorder widgets?
How do you avoid ten widgets making the same request?
How would you keep a live widget from running in a hidden tab?
Tips
Ask clarifying questions first.
Name the trade-off between many requests and one combined request.
Cover failure, loading, performance and accessibility.
Evaluation rubric
Structures the solution into clear layers.
Handles loading, errors, freshness and performance.
Explains trade-offs and decisions.
185.angular-0185Hardsenior
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:
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.
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').
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.
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).
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.
API layer. One typed service per resource, using httpResource or HttpClient. Central error mapping (validation errors from the server mapped to form controls).
Safety nets: confirm dialogs for destructive actions, optimistic updates only where rollback is easy, canDeactivate guard for unsaved forms, and idempotent endpoints for retries.
Audit and observability: the server records who did what. The client sends a correlation id, and logs errors.
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.
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.
186.angular-0186Hardsenior
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.
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.
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.
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.
Assets: logo and favicon URLs come from the theme. Use NgOptimizedImage for the logo.
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).
Dark mode: a second set of tokens under [data-theme="dark"] or prefers-color-scheme. The theme service sets the attribute.
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.
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.
187.angular-0187Hardsenior
How would you implement feature flags in an Angular app (a service, a template directive and a route guard), and what risks do flags bring?
Load flags at start-up into a signal based service with safe defaults, read them in components through a computed or a structural directive, and protect routes with a canMatch guard so disabled features are not even downloaded. Treat flags as temporary: name them, give them owners and remove them, and test both states.
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. FeatureFlagService holds the flags in a signal (Record<string, boolean>), and exposes isEnabled(name). Flags are loaded before the first render with provideAppInitializer from 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 or computed makes the UI update when flags change.
Directive. *appFeature="'newDashboard'" renders content only when the flag is on, and supports an else template. 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. canMatch is better than canActivate for 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.
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.
188.angular-0188Hardsenior
A form with hundreds of controls (a long admission form or a spreadsheet-like grid) is slow to type in. How do you find the cause and speed it up?
Typing is slow when each key triggers validation, valueChanges subscribers and change detection for the whole form. Profile first, then reduce work: updateOn blur for heavy controls, OnPush sub-form components, debounced and async validation, fewer valueChanges subscriptions, track in lists, virtual scrolling for many rows, and splitting the form into steps.
Full answer
Start by measuring. Use the browser Performance panel while typing in a field, and the Angular DevTools profiler. Look for long tasks per keystroke, and check which components are checked and which functions are slow (validators, template methods, valueChanges subscribers). Without that, you may optimise the wrong thing.
Typical causes and fixes:
Every change triggers heavy work. By default, a control updates on each input event: it runs validators, updates its parent group (which runs the group validator and recalculates validity up to the root), and emits valueChanges and statusChanges. With hundreds of controls, a group validator or a root valueChanges subscriber that loops over everything is expensive. Fixes: updateOn: 'blur' (or 'submit') for the form, group or specific controls, so work happens once when the user leaves a field. Debounce expensive reactions with debounceTime. Avoid subscribing to form.valueChanges for the whole form, and subscribe to the control that matters.
Validators are slow or call servers. Keep synchronous validators cheap. Async validators should be debounced (timer in the validator) and run only if the sync validators pass.
Change detection checks everything. Split the form into sub-form components, each with OnPush, and pass the child FormGroup down. With ControlContainer (viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]) sub-components can use formControlName inside the parent form. A keystroke in one section then only checks that section.
Template methods and getters. A method like getError('email') that calls form.get(...) many times per check adds up. Use direct control references (form.controls.email), @let, or computed values, and show errors only for touched controls.
Many rows. In a FormArray of hundreds of rows, use track on a stable id, virtual scrolling for the rows that are visible, or pagination. Create row groups lazily.
Too much on the page. Split a long form into steps or accordions rendered on demand (@defer, @if). Autosaving the form can use a debounced write, not an immediate write per key.
Template-driven forms with ngModel on hundreds of inputs are slower than reactive forms because each control registers asynchronously. Prefer reactive forms for large screens.
After each change, measure again with the same typing test. Keep the gains with a small performance test or a budget in review.
typescript
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
// Captured in Karma (Angular 20.3): three input events, then one blur
// default controls: valueChanges emissions while typing = 3, after blur = 3
// updateOn 'blur': valueChanges emissions while typing = 0, after blur = 1
export const counts = { change: 0, blur: 0 };
@Component({
selector: 'app-update-on-demo',
imports: [ReactiveFormsModule],
template: `
<input id="a" aria-label="Default" [formControl]="onChange" />
<input id="b" aria-label="On blur" [formControl]="onBlur" />
`,
})
export class UpdateOnDemoComponent {
readonly onChange = new FormControl('', { nonNullable: true });
readonly onBlur = new FormControl('', { nonNullable: true, updateOn: 'blur' });
constructor() {
this.onChange.valueChanges.subscribe(() => counts.change++);
this.onBlur.valueChanges.subscribe(() => counts.blur++);
}
}
Angular 20.3, strict template check passes. A Karma test sends three input events to a field and counts valueChanges emissions for the default setting and for `updateOn: 'blur'`: 3 and 0 while typing, and 1 after blur (the captured numbers are in the comment).
Key points
Profile typing first. Look for validators, `valueChanges` subscribers and wide change detection.
Reduce work per keystroke with `updateOn: 'blur'`, debounce, and narrow subscriptions.
Split into `OnPush` sub-form components using `ControlContainer`. Use `track`, virtual scroll or steps for big lists.
Prefer direct control references over template methods, and reactive over template-driven forms for big forms.
Common mistakes
Subscribing to the whole form's `valueChanges` to do heavy work.
Optimising without a profile.
Rendering all rows of a huge `FormArray` at once.
Follow-ups
What does `updateOn: 'blur'` change for validation messages?
How does `ControlContainer` let a child component join the parent form?
When would you split the form into steps?
Tips
Start with measuring.
Group the causes: work per key, check scope, and size.
Mention a measurable test after the fix.
Evaluation rubric
Finds causes through profiling.
Gives targeted fixes for validation, change detection and size.
Verifies with measurement.
189.angular-0189Hardsenior
Write an interceptor that refreshes an expired access token on a 401 response, makes only one refresh call when several requests fail together, and retries the failed requests.
On a 401, start one refresh request and share it with every request that fails while it is in flight (a stored shared observable, cleared when it finishes). Each failed request waits for the shared result, then retries once with the new token. If refresh fails, clear the session and send the user to login.
Full answer
When an access token expires, a page often has several requests in flight. If each one starts its own refresh, the server may see several refresh calls, and with rotating refresh tokens only the first succeeds and the others fail, logging the user out by mistake. The pattern that solves it is single flight: one refresh, many waiters.
Design:
Attach the token. The interceptor clones each API request with Authorization: Bearer <token>.
Catch 401. Use catchError on the response. Only handle HttpErrorResponse with status 401, only for your API, and never for the refresh request itself (or you would loop).
Share one refresh. Keep a field refresh$: Observable<string> | null in the auth service. If it is null, create it: http.post('/auth/refresh', ...), map to the new token, store the token, and pipe shareReplay(1) and finalize(() => this.refresh$ = null). If it already exists, reuse it. All failing requests subscribe to the same observable.
Retry once. After the refresh emits, switchMap to next(withToken(req, newToken)). Mark the retried request (for example with an HttpContextTokenRETRIED) so a second 401 does not start another refresh, and instead logs the user out.
Refresh failure. If the refresh call fails (refresh token expired), clear the session, navigate to login with a return URL, and propagate the error.
Proactive refresh (optional). Refresh slightly before expiry using the token's expiry time, to avoid most 401 responses. Keep the 401 handler anyway for clock differences and revoked sessions.
Edge cases: a request that starts while a refresh is running still sends the old token and gets a 401, but it then joins the same shared refresh and retries, so it works. Making new requests wait for a running refresh before they are sent saves that extra failed call, and is an optional improvement. Non-idempotent requests (POST) can be retried safely after a 401 because the server rejected them before processing. Do not retry other errors here.
Test with HttpTestingController: make three calls, answer them with 401, expect exactly one refresh request, flush it, then expect three retried requests with the new token.
Angular 20.3, type-checked. A Karma test with `HttpTestingController` sends three parallel requests that get 401, checks that exactly one refresh request is made, then checks that all three are retried with the new token. A second test checks that a failed refresh clears the session.
Key points
Several parallel 401 responses must cause one refresh request (single flight).
Store the shared refresh observable in the auth service, clear it in `finalize`.
Retry each request once with the new token, and guard against loops with a context flag.
If refresh fails, clear the session and go to login.
Common mistakes
Each failed request starting its own refresh.
Retrying the refresh request itself on 401 and looping.
Retrying forever when the new token is also rejected.
Follow-ups
Why can parallel refresh calls log the user out with rotating refresh tokens?
How would you refresh before the token expires?
Where do you keep the refresh token?
Tips
Name the race condition first.
Describe the shared observable and its clean-up.
Say how you test it with `HttpTestingController`.
Evaluation rubric
Prevents duplicate refresh calls.
Retries once and prevents loops.
Handles refresh failure and describes a test.
190.angular-0190Hardsenior
Design a real-time notification feature (bell icon with unread count, live updates, history). How do you choose between WebSocket, server-sent events and polling, and how is it built in Angular?
Choose the transport by need: polling is simplest, server-sent events give one-way push over HTTP with automatic reconnect, and WebSocket gives two-way messages. In Angular, one service owns the connection, exposes a signal for the unread count and a stream for new items, reconnects with backoff, pauses when the tab is hidden, and loads history over normal HTTP.
Full answer
Clarify first: how fast must a notification arrive (seconds or a minute), how many users are connected, whether the client must send messages back, and what happens when the user is offline.
Transport choice:
Polling (timer(0, 30000) plus an HTTP call): simplest, works through every proxy and cache, easy to scale. Cost: delay and wasted requests. Good when a minute of delay is fine.
Server-sent events (SSE, EventSource): one-way push over a normal HTTP connection. Browser reconnects automatically and sends Last-Event-ID, so the server can resume. Works well through HTTP/2. Good for notifications and live feeds. Limits: text only, one direction, and EventSource cannot set headers (use cookies or a token in the URL carefully).
WebSocket: two-way, low latency, binary support. Needs sticky routing or a message broker, heartbeats and manual reconnect. Choose it for chat, collaboration or when the client sends frequent messages.
Back end shape (briefly): the server writes notifications to a database, and publishes events to a broker (Redis, Kafka) so any instance can push to the user's connection. History and unread count come from normal REST endpoints.
Angular design:
NotificationService (root) owns the connection. It exposes unread = signal(0) and incoming$ (Observable, shared). Components never open sockets.
Start the connection after login, close it on logout. Use RxJS webSocket() or an Observable that wraps EventSource, with retry and exponential backoff and jitter, and a cap.
Initial state: load the last items and the unread count by HTTP, then merge live items (de-duplicate by id, because an item can arrive twice).
UI: a bell button with aria-live="polite" count, a panel with @for and track id, mark as read (optimistic update with rollback), and a "new items" toast through LiveAnnouncer for screen readers.
Efficiency: pause or slow down when the tab is hidden (visibilitychange), run the socket outside the Angular zone if messages are frequent, and batch updates so the UI refreshes at most once per animation frame.
Multiple tabs: use BroadcastChannel or a SharedWorker to share one connection.
Failure: show a small "reconnecting" state, fall back to polling if the connection keeps failing, and replay missed items after reconnect using the last id.
Name the trade-offs openly: SSE is the simplest correct choice for one-way notifications, WebSocket is justified by two-way needs, and polling is a fine start.
Angular 20.3 and RxJS 7.8, type-checked. The service logic (merge, de-duplicate, unread count) was run with a fake stream in a Karma test. No real WebSocket or EventSource server was available.
Key points
Polling is simplest, SSE is one-way push with auto reconnect, WebSocket is two-way. Pick by need.
One root service owns the connection and exposes a signal and a stream.
Backoff with jitter, de-duplicate by id, resume with the last id, pause in hidden tabs.
Load history by REST, and make the UI accessible with live regions.
Common mistakes
Opening a WebSocket in every component.
Reconnecting immediately in a tight loop after a failure.
Showing duplicates after a reconnect.
Follow-ups
How does `Last-Event-ID` help after a reconnect?
How would you share one connection between browser tabs?
When would you choose WebSocket over SSE?
Tips
Ask about latency and direction first.
Compare the three transports in one sentence each.
Mention backoff, duplicates and accessibility.
Evaluation rubric
Chooses a transport with reasons.
Designs a service with state, reconnect and de-duplication.
Covers UI, accessibility and efficiency.
191.angular-0191Hardsenior
Your company has three Angular apps with inconsistent UI. How do you decide between Angular Material, another library, or a custom design system, and how do you build and roll it out?
Decide with criteria: brand fit, accessibility needs, time, team size and long-term maintenance. A common answer is to build a thin design system on top of the CDK or Material (tokens, a few wrapped components), publish it as a versioned library with docs and tests, and roll it out gradually with clear ownership and a deprecation policy.
Full answer
This is a decision and organisation question, not only a technical one. Structure the answer in steps.
Clarify goals: consistency across apps, faster delivery, accessibility compliance, brand identity, and who will maintain it. Count how many teams and apps will use it, and which frameworks (all Angular, or others too).
Options:
Use an existing library as is (Angular Material, PrimeNG, Spartan or similar). Fast, accessible, well tested. Cost: the look follows the library, deep customisation can be painful, and you depend on its release plan.
Build a custom design system on the CDK. Full control of look and behaviour, and the CDK gives accessible primitives (overlay, a11y, listbox, menu, drag-drop). Cost: a team to maintain components, docs and accessibility.
A hybrid (most common): adopt Material or CDK primitives, theme them with your design tokens, and wrap them in your own components (school-button, school-form-field) so apps depend on your API, not the underlying library. You can replace pieces later.
Web Components (Angular Elements or a Web Component library like Lit or Shoelace) when apps use different frameworks.
Decision criteria: brand distance from Material, accessibility requirements, team capacity (a design system needs at least a small dedicated team), release speed, and the cost of switching later.
Build:
Design tokens first (colour, spacing, type, radius), as CSS custom properties, owned with designers.
A workspace library (ng-packagr), standalone components, signal inputs, OnPush, secondary entry points for tree shaking.
Docs and examples with Storybook or similar, each component showing states and accessibility notes.
Tests: component tests with harnesses, axe checks, and visual regression tests.
Semantic versioning and a changelog, with ng update style migrations when you break things.
Roll out: start with the highest value components (button, form field, table, dialog) and one pilot app. Provide a migration guide and codemods where possible. Measure adoption.
Governance: a contribution process, an owner team, a deprecation policy (announce, warn, remove after two releases), and a way for product teams to request components.
Risks: a design system becomes a bottleneck if it is slow to respond, or becomes shelfware if it does not serve real screens. Keep it small, useful and driven by real use.
Angular 20.3, type-checked. The sample is a wrapper component with signal inputs that hides the underlying library behind the company API. It was not published as a package here.
Key points
Compare using a library, a custom system, and a hybrid built on CDK or Material with your own wrapper API.
Decide on brand fit, accessibility, team capacity and switching cost.
Build tokens, a versioned library, docs, harness tests, axe checks and visual tests.
Roll out with a pilot, migration guides, ownership and a deprecation policy.
Common mistakes
Building a full custom library without a team to maintain it.
Letting apps import the third party library directly, so a switch is hard.
Skipping documentation and versioning.
Follow-ups
How would you handle a breaking change in the library?
What does wrapping Material components give you?
How do you measure adoption?
Tips
Frame it as a decision with criteria.
Recommend the hybrid and justify it.
Include governance, not only code.
Evaluation rubric
Compares the options with criteria.
Describes how to build and test the system.
Includes rollout and governance.
192.angular-0192Hardsenior
How do you test time-based RxJS code (debounce, switchMap, retry) with the TestScheduler and marble diagrams, without waiting for real time?
TestScheduler.run runs the code in virtual time. Marble strings draw streams: a dash is one millisecond, letters are values, | is completion, # is an error, ^ and ! mark subscription and unsubscription. cold and hot create inputs, and expectObservable compares the output with an expected marble, so tests are fast and exact.
Full answer
Testing time based code with real timers is slow and flaky. fakeAsync helps for promises and timers in Angular tests, but for RxJS pipelines with several operators the TestScheduler gives exact, readable tests.
How it works: new TestScheduler(assertDeepEqual) takes a function that compares actual and expected notifications. In scheduler.run(helpers => { ... }), all RxJS schedulers (timers, debounceTime, delay, interval) use virtual time, so a pipeline that takes seconds runs in microseconds. You describe inputs and expected outputs as marble diagrams.
Marble syntax inside run:
- advances one millisecond. A space is ignored.
A letter or digit is a value emitted at that frame. The value is looked up in the optional values object ({ a: 'ang', b: 'angular' }).
| is completion, # is an error.
() groups several events in one frame, such as (ab|).
^ marks the subscription point of a hot observable, and ! marks unsubscription.
Time can be written as a number with unit: a 299ms b, which is easier than counting dashes.
Helpers: cold('--a|') (starts when subscribed), hot('--a--b') (already running), expectObservable(stream$).toBe('...', values), and expectSubscriptions(source.subscriptions).toBe('^--!') to check that switchMap unsubscribed from the previous inner observable at the right time.
What to test with it: a search pipe (debounce plus distinctUntilChanged plus switchMap), retry with backoff (check the exact delays), polling with takeUntil, and timeouts. In the example, typing "a", "ab" quickly and "abc" later gives only the results for "ab" and "abc", and the earlier request for "a" never runs.
Tips: keep the stream under test in a function that takes its dependencies (the scheduler is global in run, so no injection is needed). Do not mix run with real asynchronous code. For streams inside Angular components, test the pure pipeline function with marbles and keep the component test small.
typescript
import assert from 'node:assert';
import { Observable, debounceTime, distinctUntilChanged, map, switchMap, timer } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
function search(terms$: Observable<string>, delayMs: number): Observable<string> {
return terms$.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term) => timer(delayMs).pipe(map(() => `results for ${term}`))),
);
}
const scheduler = () => new TestScheduler((actual, expected) => assert.deepStrictEqual(actual, expected));
scheduler().run(({ hot, expectObservable }) => {
const typed = hot('a 100ms b 500ms c 500ms |', { a: 'a', b: 'ab', c: 'abc' });
// "a" is replaced by "ab" within 300 ms, so only "ab" and "abc" reach the server.
expectObservable(search(typed, 50)).toBe('- 450ms x 500ms y 150ms |', {
x: 'results for ab',
y: 'results for abc',
});
});
console.log('search marble test passed');
try {
scheduler().run(({ hot, expectObservable }) => {
const typed = hot('a 400ms |', { a: 'a' });
expectObservable(search(typed, 50)).toBe('- 10ms x |', { x: 'results for a' }); // wrong on purpose
});
} catch {
console.log('wrong expectation was detected');
}
RxJS 7.8. The script was run in Node 24 twice with identical output. The marble assertions pass, and a deliberately wrong expectation was also run to confirm that a mismatch throws.
Key points
`TestScheduler.run` uses virtual time, so time based streams are tested instantly.
Marbles: `-` 1 ms, letters values, `|` complete, `#` error, `^` and `!` subscribe and unsubscribe.
Use `cold`, `hot`, `expectObservable` and `expectSubscriptions`.
Test pipelines as functions. Keep component tests small.
Common mistakes
Using real timers and `setTimeout` in RxJS tests.
Forgetting that a `-` is one millisecond inside `run`.
Mixing real asynchronous code with `run`.
Follow-ups
How would you check the delays of a retry with backoff?
When is `fakeAsync` enough?
What does `expectSubscriptions` verify?
Tips
Explain virtual time first.
Draw one marble diagram of a search box.
Mention subscription checks for `switchMap`.
Evaluation rubric
Explains virtual time and marble syntax.
Writes a correct marble test.
Knows what to test and when to use `fakeAsync`.
193.angular-0193Hardsenior
What would you check in a security review of an Angular application, and how do Content Security Policy and Trusted Types fit in?
Angular escapes templates and sanitizes risky bindings, but a review also checks bypass calls, direct DOM use, token storage, dependency risk, server headers and the API. A strict Content Security Policy limits what scripts can run, and Trusted Types force dangerous DOM sinks to accept only trusted values, which Angular supports.
Full answer
A review has two parts: the code in the app, and the environment around it (headers, dependencies, server). The front end is the visible part, but real protection must also exist on the server.
Code checklist:
XSS sinks. Search for bypassSecurityTrust, innerHTML on nativeElement, document.write, eval, new Function, insertAdjacentHTML, and [innerHTML] with unvalidated data. Each one needs a justification. Prefer Angular's sanitization, and validate or sanitize with an allowlist library before trusting.
URLs. Links and iframes built from user input must be validated (allow only https: and known hosts). Check target="_blank" links use rel="noopener" (modern browsers imply it, but be explicit for older ones).
Authentication. Where are tokens stored? Prefer in memory or HTTP-only secure cookies (with a BFF) over localStorage. Use the code flow with PKCE. Never log tokens. Check logout clears state.
CSRF. With cookie-based sessions, use SameSite cookies and the CSRF token pattern. Angular's HttpClient reads an XSRF-TOKEN cookie and sends X-XSRF-TOKEN for same-origin mutating requests. Bearer tokens in headers are not sent automatically by the browser, so they avoid classic CSRF.
Data exposure. No secrets in the bundle (API keys that grant write access, private URLs). Everything in the client is public.
Authorization. Guards and hidden buttons are only user experience. Confirm the API enforces access.
Error handling. Do not show stack traces or server messages to users, and do not send personal data to logging tools.
Environment checklist:
Dependencies: npm audit, lock files, automated updates, review of new packages, and removal of unused ones.
Headers: Content-Security-Policy, X-Content-Type-Options: nosniff, Referrer-Policy, Strict-Transport-Security, frame-ancestors (clickjacking), and correct CORS on the API.
Content Security Policy (CSP): a header that tells the browser which sources of scripts, styles and connections are allowed. A strict CSP (nonce or hash based, no unsafe-inline) means injected inline scripts do not run, which limits XSS damage. Angular supports CSP: set ngCspNonce on the root element (the server provides the nonce per response) so styles that Angular adds are allowed, and the build can inline critical CSS with nonce support.
Trusted Types: a browser feature (require-trusted-types-for 'script') that makes DOM sinks such as innerHTML and script.src accept only special objects, not strings. Angular provides policies (angular, angular#bundler) so its own code works, and a violation shows where untrusted code touches a sink. Start in report-only mode, fix violations, then enforce.
Present findings with severity and fix, and automate checks (lint rules, dependency scans, CSP tests) so the review is repeatable.
Angular 20.3, type-checked. The XSRF header behaviour was checked in Karma for the earlier CSRF item, not again here. The header helper was run in Node twice with identical output. The CSP header values are an example and were not tested against a browser here.
Key points
Review code (bypass calls, DOM sinks, URLs, token storage, secrets) and the environment (dependencies, headers, CORS).
Guards are UX. The server enforces authorization.
A strict CSP limits script execution. Use `ngCspNonce` with Angular.
Trusted Types restrict dangerous sinks, and Angular has policies. Start in report-only mode.
Common mistakes
Storing long-lived tokens in `localStorage`.
Adding `unsafe-inline` to make a CSP error disappear.
Trusting client side checks.
Follow-ups
How does Angular's XSRF protection work?
What does `ngCspNonce` do?
How do you roll out a CSP safely?
Tips
Give a structured checklist: code, then environment.
Explain CSP and Trusted Types in one sentence each.
Mention report-only rollout.
Evaluation rubric
Covers code and environment checks.
Explains CSP and Trusted Types correctly.
Advises a safe rollout and automation.
194.angular-0194Hardsenior
Build a file upload with progress, cancel and client-side validation using HttpClient. How do you report progress, and what must still be checked on the server?
Send FormData with reportProgress and observe events. Map UploadProgress events to a percentage and the final Response event to done. Cancel by unsubscribing (which aborts the request). Check size and type on the client for quick feedback, but always validate again on the server.
Full answer
Uploads need three things that normal GET and POST calls do not: progress, cancel and validation.
Progress. Use http.post(url, formData, { reportProgress: true, observe: 'events' }). The observable emits HttpEvent objects:
HttpEventType.Sent: the request left.
HttpEventType.UploadProgress: has loaded and total (bytes). The percentage is Math.round(100 * loaded / total). total can be undefined when the size is unknown.
HttpEventType.ResponseHeader and DownloadProgress: for the response.
HttpEventType.Response: the final body. Treat this as success.
Backend note: the Fetch API cannot report upload progress, and the XHR API can. In Angular 20 the XHR backend is the default, so reportProgress: true works, and adding withFetch() removes upload progress. In the newest Angular documentation, fetch is the default backend and withFetch() is deprecated. There you configure provideHttpClient(withXhr()) for uploads that need progress, and use the options reportUploadProgress and reportDownloadProgress (the single reportProgress option is deprecated, and reportUploadProgress with the fetch backend throws an error). Check which backend your version uses.
Cancel. Unsubscribing from the observable aborts the request (xhr.abort()). Put it behind takeUntil(cancel$) or keep the Subscription and call unsubscribe() from a Cancel button. Reset the progress state afterwards. In a component, add takeUntilDestroyed() too, so leaving the page cancels the upload.
Client-side validation (fast feedback, not security): check file.size against a limit, check file.type or the extension against an allowlist, and check the count. Show clear messages. Use accept=".pdf,.png" on the input as a hint only, because users can bypass it.
Server-side validation (the real protection): size limit at the proxy and in the app, content type detection by reading the file (not trusting the name or MIME type sent by the client), virus scanning, a safe storage name (never use the client file name as a path), authentication and authorization, and rate limits. For large files consider chunked or resumable uploads (tus protocol) and direct upload to object storage with a signed URL, which also avoids loading the file through your server.
UI details: disable the button while uploading, announce progress to screen readers (<progress> element with value and max, or aria-live text), and show errors with a retry option.
Test with HttpTestingController: req.event({ type: HttpEventType.UploadProgress, loaded: 50, total: 100 }) simulates progress, and flush completes the request.
typescript
import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, filter, map } from 'rxjs';
export type UploadState = { kind: 'progress'; percent: number } | { kind: 'done'; body: unknown };
const MAX_BYTES = 5 * 1024 * 1024;
const ALLOWED = ['application/pdf', 'image/png'];
export function validateFile(file: { size: number; type: string }): string | null {
if (file.size > MAX_BYTES) return 'File is larger than 5 MB';
if (!ALLOWED.includes(file.type)) return 'Only PDF and PNG files are allowed';
return null; // the server must still check
}
@Injectable({ providedIn: 'root' })
export class UploadService {
private readonly http = inject(HttpClient);
upload(file: File): Observable<UploadState> {
const body = new FormData();
body.append('file', file, file.name);
// Angular 20: reportProgress. Newer versions: reportUploadProgress: true (with withXhr()).
return this.http.post('/api/upload', body, { reportProgress: true, observe: 'events' }).pipe(
map((event: HttpEvent<unknown>): UploadState | null => {
if (event.type === HttpEventType.UploadProgress) {
return { kind: 'progress', percent: event.total ? Math.round((100 * event.loaded) / event.total) : 0 };
}
return event.type === HttpEventType.Response ? { kind: 'done', body: event.body } : null;
}),
filter((state): state is UploadState => state !== null),
);
}
}
Angular 20.3, type-checked with ngc. No Karma test was run for this item. The backend limitation (fetch has no upload progress; use the XHR backend) comes from the Angular HttpClient documentation on angular.dev, checked in December 2026, and was not tested here. The snippet uses `reportProgress`, which is the option in Angular 20.3. The current docs use `reportUploadProgress` and `reportDownloadProgress` with `provideHttpClient(withXhr())`. Those APIs are not in the installed 20.3.
Key points
Use `reportProgress: true` with `observe: 'events'`. `UploadProgress` gives `loaded` and `total`.
Unsubscribing aborts the request. Use it for cancel and for leaving the page.
Client checks give quick feedback. Server checks are the real validation.
The fetch backend has no upload progress. Use the XHR backend (the default in Angular 20, or `withXhr()` in newer versions) for uploads that need progress.
Common mistakes
Trusting `accept` or the file extension as validation.
Using the fetch backend and expecting upload progress.
Using the client file name as a storage path on the server.
Follow-ups
How would you resume an interrupted large upload?
Why upload directly to object storage with a signed URL?
How do you make the progress accessible?
Tips
List the event types you use.
Separate client convenience checks from server security checks.
Mention cancel through unsubscribe.
Evaluation rubric
Implements progress and completion mapping correctly.
Cancels cleanly and validates on both sides.
Knows the fetch backend limitation.
195.angular-0195Hardsenior
Design an offline-first feature (for example, a teacher marking attendance in a classroom with bad internet). How do you store changes, sync them later and handle conflicts in Angular?
Save every change locally first (IndexedDB), show it in the UI at once, and put it in an outbox queue. A sync service sends queued changes when the network is back, with idempotency keys so retries are safe, and resolves conflicts with a clear rule. The service worker caches the app shell and read data, and the UI shows sync status.
Full answer
Clarify the requirement: which actions must work offline (read lists, mark attendance), how long a device can be offline, whether several people edit the same data, and what is acceptable when two edits clash.
Design:
App shell and assets: the Angular service worker (@angular/service-worker) caches the app files, so the app starts offline. Use dataGroups for read-only API data (class lists) with a freshness or performance strategy and a sensible age.
Local data: store data in IndexedDB (use a small wrapper such as Dexie or idb), not localStorage (too small and synchronous). The UI reads from the local store through a service that exposes signals. This is the "local first" idea: the screen never waits for the network.
Writing: every user action becomes a command in an outbox table: { id (uuid), type, payload, createdAt, status }. The UI updates the local data at once (optimistic), and shows a small "pending" mark for items that are not synced.
Sync service: when navigator.onLine is true and the app is online (the online event is a hint, a failed request is the truth), it sends outbox items in order, one by one or in batches. Success removes the item. A network error keeps it and retries with backoff. A validation error (4xx) marks it as failed and shows it to the user. Use the Background Sync API where supported to sync after the tab closes, but do not depend on it (Safari has no support).
Idempotency: the client sends the command id as an idempotency key, and the server stores processed ids, so a retry after a timeout does not create duplicates.
Conflicts: choose a rule. Last write wins (simple, may lose data), per field merge, version numbers (the server rejects an update if the base version is old, and the client shows a merge dialog), or CRDTs for collaborative text. For attendance, "per student per date, latest timestamp wins" is usually enough, and the audit log keeps the history.
Pull: after pushing, fetch changes since the last sync token (delta sync), and merge into IndexedDB.
UX: show an offline banner, a count of unsynced items, a retry button, and the time of the last sync. Tell users clearly when the data may be old.
Security and cleanup: the local database holds personal data, so clear it on logout, and avoid storing more than needed. Encrypt only if the threat model needs it, since keys in the browser are hard to protect.
Testing: simulate offline with the browser's network throttle, run Playwright tests with context.setOffline(true), and test the sync service with a fake clock and fake API.
State the trade-off: offline-first adds a lot of complexity (storage, sync, conflicts, migrations), so build it only for features where users really lack connectivity.
typescript
export interface Command {
id: string;
type: 'mark-attendance';
payload: { studentId: number; date: string; present: boolean };
}
export class Outbox {
private readonly queue: Command[] = [];
add(command: Command): void {
this.queue.push(command);
}
get pending(): number {
return this.queue.length;
}
// Sends commands in order. Stops at the first network failure and keeps the rest.
async flush(send: (command: Command) => Promise<'ok' | 'rejected'>): Promise<{ sent: number; rejected: Command[] }> {
let sent = 0;
const rejected: Command[] = [];
while (this.queue.length > 0) {
const next = this.queue[0];
try {
const result = await send(next); // the command id is the idempotency key
this.queue.shift();
if (result === 'ok') sent++;
else rejected.push(next);
} catch {
break; // offline: try again later
}
}
return { sent, rejected };
}
}
// Demo: the first send fails (offline), the second attempt works.
const outbox = new Outbox();
outbox.add({ id: 'c1', type: 'mark-attendance', payload: { studentId: 1, date: '2026-12-04', present: true } });
outbox.add({ id: 'c2', type: 'mark-attendance', payload: { studentId: 2, date: '2026-12-04', present: false } });
let online = false;
const send = async (): Promise<'ok' | 'rejected'> => {
if (!online) throw new Error('offline');
return 'ok';
};
const first = await outbox.flush(send);
console.log('offline flush:', first.sent, 'sent,', outbox.pending, 'pending');
online = true;
const second = await outbox.flush(send);
console.log('online flush:', second.sent, 'sent,', outbox.pending, 'pending');
Angular 20.3, type-checked. The outbox logic was run in Node 24 twice with identical output, using an in-memory queue and a fake send function that fails while offline and succeeds when online. IndexedDB, the service worker and Background Sync were not run here.
Key points
Local first: write to IndexedDB, update the UI at once, queue commands in an outbox.
A sync service retries with backoff and uses idempotency keys. It handles 4xx failures separately.
Pick a conflict rule (last write wins, versions with a merge, CRDT) that fits the data.
The service worker caches the shell and read data. The UI shows pending and sync status.
Common mistakes
Using `localStorage` for offline data.
Retrying without idempotency, creating duplicates.
Trusting `navigator.onLine` as proof of a working connection.
Follow-ups
How do you handle a schema change in the local database?