Questions 21–40 of 195 · 0 of 20 on this page marked learned
21.angular-0021Mediummid
How do you combine signals and RxJS with toSignal() and toObservable()? Build a debounced search as an example.
toSignal() turns an Observable into a signal and unsubscribes automatically, and toObservable() turns a signal into an Observable that emits changes. Together they let you keep UI state in signals and use RxJS operators for timing and cancellation, such as debounceTime and switchMap.
Full answer
Signals are good for current state. RxJS is good for events over time: waiting, cancelling, retrying. A real app uses both, and @angular/core/rxjs-interop joins them.
toSignal(obs$, { initialValue }) subscribes at once, stores the latest value, and unsubscribes when the owner is destroyed. Without an initialValue the type is T | undefined until the first emission. Use requireSync: true only for Observables that emit synchronously, such as BehaviorSubject. If the Observable errors, reading the signal throws the error, so handle errors in the stream first.
toObservable(sig) emits the signal's value through an effect, so it is delivered asynchronously and consecutive synchronous changes are merged into one emission.
Both need an injection context, or an injector option.
In the search example, the query is a signal bound to the input. It becomes an Observable, debounceTime(300) waits until the user stops typing, distinctUntilChanged() skips repeated values, and switchMap cancels the older HTTP request when a new one starts. The result becomes a signal for the template. Because HTTP is a one-shot Observable that completes, switchMap is the right flattening operator here.
Angular's resource and httpResource APIs (experimental in Angular 20) aim to cover simple loading cases, but RxJS stays the right choice for debouncing and complex flows.
Angular 20.3 and RxJS 7. Needs `provideHttpClient()` in the app config and an API that answers `GET /api/search?q=...` with a JSON array of strings.
Key points
`toSignal` subscribes immediately, cleans up automatically, and needs an `initialValue` (or `requireSync`).
`toObservable` emits asynchronously and merges synchronous changes.
Both need an injection context.
Use `switchMap` to cancel outdated requests, and handle errors inside the inner stream.
Common mistakes
Calling `toSignal` inside a method or event handler, outside an injection context.
Letting an HTTP error reach `toSignal`, which then throws on every read.
Putting `catchError` on the outer stream so one failure ends the whole search.
Follow-ups
Why `switchMap` and not `mergeMap` for typeahead?
What does `toObservable` emit when you set a signal twice in a row?
When would you use `resource` instead of this pattern?
Tips
Draw the pipeline: signal, observable, operators, signal. It is easy to follow.
Say where the error handling goes (inside `switchMap`). This is what interviewers check.
Show `initialValue` and say what the type becomes without it.
Evaluation rubric
Uses toSignal and toObservable correctly.
Chooses debounce, distinctUntilChanged, and switchMap with reasons.
Handles errors and injection context.
22.angular-0022Mediummid
How do you configure providers in Angular DI: useClass, useValue, useFactory, useExisting, InjectionToken and multi providers?
A provider tells an injector how to create the value for a token. useClass builds an instance of a class, useValue returns a fixed value, useFactory runs a function (which can call inject()), and useExisting makes one token an alias of another. An InjectionToken names non-class values, and multi: true collects several values under one token.
Full answer
Every DI lookup uses a token. For a class the token is the class itself. The provider says what to give for that token.
{ provide: Logger, useClass: ConsoleLogger } builds a ConsoleLogger whenever Logger is requested. This allows swapping the implementation, for example in a test. An abstract class makes a good token and type at the same time.
{ provide: APP_CONFIG, useValue: { apiUrl: '/api' } } supplies a ready-made object or constant.
{ provide: ApiClient, useFactory: () => new ApiClient(inject(APP_CONFIG)) } runs a function. Inside it you can call inject(), so the value can depend on other services or on the environment.
{ provide: OldLogger, useExisting: Logger } makes two tokens return the same instance.
multi: true lets several providers add to a list under one token, such as validators or interceptors. The injected value is an array.
Interfaces and plain objects do not exist at runtime, so they cannot be tokens. Use new InjectionToken<AppConfig>('APP_CONFIG'). A token can carry a default: new InjectionToken('X', { factory: () => ... }), and with providedIn: 'root' the token is tree-shakable and needs no registration.
Where providers are placed decides how many instances exist. ApplicationConfig.providers and providedIn: 'root' give one per app. A route's providers gives one per lazy route tree. A component's providers gives one per component instance.
The example creates a plain injector, so it runs under Node without a browser.
Tested on Angular 20.3 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`). It uses `Injector.create`, so no browser is needed. Output: the API line, the logger lines, and `validators 2 ok false`.
Key points
Provider forms: `useClass`, `useValue`, `useFactory`, `useExisting`, plus `multi`.
Use `InjectionToken` for configuration and other non-class values.
Factories can call `inject()`, which lets them depend on other tokens.
Provider location decides the lifetime and number of instances.
Common mistakes
Using an interface as a token. It is erased at compile time.
Forgetting `multi: true` and having the last provider silently replace the others.
Putting configuration in a global variable instead of a token, which makes tests harder.
Follow-ups
What is the difference between `useClass` and `useExisting`?
How would you override a root service in one lazy route only?
Why make a token tree-shakable?
Tips
Walk through one example per provider type in a single sentence each.
Explain why interfaces cannot be tokens. It is a very common trap.
Mention overriding providers in tests as the main practical benefit.
Evaluation rubric
Names and explains all provider forms.
Knows InjectionToken and multi.
Understands provider scope.
23.angular-0023Mediummid
How do functional route guards work in Angular, and how do you redirect from one?
A functional guard is a plain function typed as CanActivateFn, CanMatchFn, or similar. It uses inject() to reach services and returns true, false, a UrlTree for a redirect, or an Observable or Promise of those. Class-based guards are deprecated, and guards in the browser are for user experience, not security.
Full answer
Guards let the router allow or block a navigation. The main types:
canActivate: can this route be entered?
canActivateChild: same, for child routes.
canMatch: should this route even be considered? This also decides whether lazy code is loaded.
canDeactivate: can the user leave this route (for example unsaved changes)?
Since Angular 15 guards are plain functions: const authGuard: CanActivateFn = (route, state) => { ... }. Inside you call inject(AuthService) and inject(Router), because a guard runs in an injection context. Class-based guards (implements CanActivate) were deprecated in Angular 15.2 and the interfaces are marked deprecated, although they still run.
Return values: true allows, false cancels, and a UrlTree redirects. Prefer returning router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } }) to calling router.navigate() inside the guard. A returned UrlTree cancels the current navigation and starts the new one in a clean way, which avoids race conditions. Guards can also return an Observable or a Promise; the router uses the first emitted value.
Security point: anything running in the browser can be bypassed, so guards improve user experience by hiding pages. The server must still check permissions on every API call.
canDeactivate receives the component, so you can ask it whether the form is dirty. Reuse one guard function across routes, with route.data for options such as required roles.
Angular 20.3. `AuthService` here uses a plain signal. In a real app it would check a token or call an API.
Key points
Guards are functions with `inject()`. Class guards are deprecated.
Return `true`, `false`, or a `UrlTree` (or an Observable or Promise of these).
Redirect with `createUrlTree`, not `navigate`, inside the guard.
Browser guards are not security. The API must enforce access.
Common mistakes
Calling `router.navigate()` inside a guard and returning `true`, which can cause double navigation.
Treating a guard as the only protection for sensitive data.
Forgetting the guard runs on every navigation to that route, so slow synchronous checks hurt.
Follow-ups
What is the difference between `canActivate` and `canMatch`?
How would you pass the required role to a reusable guard?
How do you wait for an async auth check inside a guard?
Tips
Say "guards are UX, the server is security" without being asked. It is what a senior reviewer wants to hear.
Mention UrlTree redirects. It is a detail many candidates miss.
If asked about legacy, say class guards still work but are deprecated.
Evaluation rubric
Writes a functional guard with inject.
Redirects with UrlTree.
States the security limit.
24.angular-0024Mediummid
How does lazy loading work in the Angular router, and how do you configure loadComponent, loadChildren and preloading?
Lazy loading splits the app into chunks that are downloaded only when a route is first visited. Use loadComponent for a single standalone component and loadChildren for a group of child routes, both with a dynamic import(). A preloading strategy can fetch the remaining chunks in the background after start-up.
Full answer
By default, everything the app imports ends up in one initial bundle, so a big app loads slowly. Lazy loading moves rarely used areas, such as an admin panel, into separate chunks. The build tool (esbuild in the current CLI) creates a chunk wherever it sees a dynamic import().
Two forms in a route definition:
loadComponent: () => import('./report.component').then(m => m.ReportComponent) for one standalone component.
loadChildren: () => import('./admin.routes').then(m => m.ADMIN_ROUTES) for a whole child Routes array. If the file has a default export of the routes, import('./admin.routes') alone is enough.
The old NgModule form was loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule). It still works, and legacy projects use it.
The route's providers array can create services that live only in that lazy tree.
Preloading. After the first load, the router can fetch lazy chunks in the background so later navigation feels instant. withPreloading(PreloadAllModules) fetches all of them. NoPreloading is the default. For finer control, write a custom PreloadingStrategy that reads route.data['preload'], or preload on user hover.
How to check it works: run ng build and look at the output. Lazy chunks are listed separately from the initial bundle. A common mistake is importing a lazy component somewhere eagerly (for example in another component's imports), which pulls it back into the main bundle. In the browser's network tab you should see the chunk requested only when you navigate.
Angular 20.3. Place the files side by side in `src/app`. After `ng build` the admin and report code appear in their own chunk files.
Key points
`import()` creates a chunk; `loadComponent` and `loadChildren` use it for routes.
Child route arrays are exported from their own file and loaded with `loadChildren`.
`withPreloading(PreloadAllModules)` fetches chunks after start-up. A custom strategy gives control.
An eager import of the same file defeats lazy loading.
Common mistakes
Importing the lazy component in the app's root `imports`, which silently puts it back in the main bundle.
Lazy loading tiny components, where the extra network request costs more than it saves.
Not checking the build output to confirm the chunk exists.
Follow-ups
How would you preload only some routes?
What does `canMatch` have to do with lazy loading?
How do route-level `providers` change the lifetime of a service?
Tips
Say how you verify it: `ng build` output and the network tab.
Mention the eager import trap. It shows real debugging experience.
Name the legacy NgModule form so the interviewer knows you can maintain old code.
Evaluation rubric
Writes loadComponent and loadChildren correctly.
Knows preloading options.
Knows how to verify and the common trap.
25.angular-0025Mediummid
How do typed reactive forms work, including FormArray, nonNullable controls, and a custom cross-field validator?
Typed forms infer types from how you create controls, so form.value and control.value are checked by TypeScript. Use nonNullable controls to avoid null, FormArray for repeating rows, and getRawValue() to include disabled controls. A cross-field rule is a validator attached to the group, not a control.
Full answer
Since Angular 14, FormControl, FormGroup, and FormArray carry types. If you write new FormControl(''), its type is FormControl<string | null>, because reset() sets it back to null. Two ways to avoid null:
new FormControl('', { nonNullable: true }), or
inject(NonNullableFormBuilder) (or fb.nonNullable), where all controls are non-null by default and reset() returns to the initial value.
form.value has type Partial<...>, since disabled controls are left out of it. To get every control, including disabled ones, with full types, call form.getRawValue().
FormArray<FormGroup<...>> handles repeating rows, such as the questions in a quiz. Add rows with push, remove with removeAt, and render with @for (row of form.controls.questions.controls; track row).
Validators are functions of type ValidatorFn: they receive the control and return null when valid, or an object of errors. A rule across two fields (pass mark must not exceed total marks) belongs on the parent group, since only the group can see both controls. Show its error with form.errors?.['passTooHigh'].
Other typed tools: FormRecord for a dynamic set of controls with the same type, and UntypedFormGroup as an escape hatch while migrating old code. Async validators return an Observable or Promise and run only after sync validators pass.
Remember to mark controls and groups as touched before showing errors, so users see them on submit.
Angular 20.3, strict template type-checking passes. The same validator function can also be unit tested without rendering.
Key points
Types are inferred; use `nonNullable` to avoid `null` from `reset()`.
`value` is partial (disabled controls omitted); `getRawValue()` is complete.
A cross-field validator is attached to the group.
`FormArray` plus `push` and `removeAt` handle repeating rows.
Common mistakes
Putting a cross-field rule on one control, where it cannot see the other control reliably.
Reading `form.value.total` and forgetting it can be `undefined` in the type.
Using `UntypedFormGroup` out of habit and losing all type safety.
Follow-ups
How would you write an async validator that checks a username on the server?
What is the difference between `valueChanges` and `statusChanges`?
When would you choose `FormRecord`?
Tips
Explain why `reset()` makes values `null` by default. It shows you understand the types, not only the syntax.
Mention that disabled controls are excluded from `value`.
Keep validators as small pure functions and say they are easy to unit test.
Evaluation rubric
Understands inferred types and nonNullable.
Builds a FormArray and a group-level validator.
Knows value versus getRawValue.
26.angular-0026Mediummid
How do you write functional HTTP interceptors for authentication and error handling, and in what order do they run?
A functional interceptor is a function of type HttpInterceptorFn that receives the request and a next handler. Register interceptors with provideHttpClient(withInterceptors([...])). Requests are immutable, so you clone them to change them. Requests pass through the list in order and responses come back in reverse.
Full answer
An interceptor sits between your code and the network. It can change every outgoing request or every response without touching each service. Typical jobs are adding an auth header, showing a global error message, logging, or retrying.
It runs in an injection context, so inject() works. HttpRequest objects are immutable. To change one you call clone(). The returned Observable is the response stream, so operators such as catchError can run on it.
Registration: provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])). Order: for a request, the first interceptor runs first and the last runs closest to the network. For the response, the order is reversed. This is like walking into a building through several doors and leaving through the same doors in reverse.
Class-based interceptors (implements HttpInterceptor, registered with the HTTP_INTERCEPTORS token) are legacy. They can still be used with withInterceptorsFromDi().
Security care: add the token only to your own API origin, not to every URL, or you will leak the token to third parties. Another trap is blindly handling 401 by refreshing the token in many parallel requests. Use a single shared refresh, usually with shareReplay.
A global error interceptor should rethrow the error (throwError) after reporting it, so calling code can still react.
Angular 20.3. The auth interceptor only touches requests that start with the API prefix. The error interceptor rethrows.
Key points
Interceptors are `HttpInterceptorFn` functions, registered with `withInterceptors([...])`.
Requests are immutable, so use `req.clone(...)`.
Order: request goes first to last, response goes last to first.
Attach tokens only to your own API, and rethrow errors after handling them.
Common mistakes
Adding the `Authorization` header to every request, including third-party URLs.
Swallowing the error in the interceptor so the caller thinks the call succeeded.
Modifying `req.headers` directly. It is immutable and the change is ignored.
Follow-ups
How would you skip the auth header for one specific request?
How do you avoid many parallel token refreshes?
How do class-based interceptors differ?
Tips
Mention origin checks for the token. It is a security point that stands out.
Draw the doors-in-and-out picture for the order question.
Say that rethrowing preserves the caller's error handling.
Evaluation rubric
Writes a functional interceptor with clone.
States ordering correctly.
Handles errors and token scope safely.
27.angular-0027Mediummid
What is the difference between switchMap, mergeMap, concatMap and exhaustMap, and when do you use each?
All four map each outer value to an inner Observable and flatten the result, but they handle overlap differently. switchMap cancels the previous inner stream, mergeMap runs all in parallel, concatMap queues them in order, and exhaustMap ignores new values while one is running.
Full answer
When each outer value starts an inner Observable (for example an HTTP call), the question is what to do if a new value arrives before the previous inner stream has finished.
switchMap: cancel the old inner stream and switch to the new one. Use it for typeahead search, route-parameter loading, or "latest value wins" cases. Cancelling an HTTP request also avoids showing stale data.
mergeMap: start the new one and keep the old ones running. Results can arrive in any order. Use it for independent parallel work, such as deleting many items. Pass a concurrency limit as the second argument when needed.
concatMap: wait for the old one to finish, then start the next, so order is kept. Use it when order matters, such as saving edits one after another.
exhaustMap: ignore new outer values while an inner stream is running. Use it for "submit" or "login" buttons to stop double clicks.
A queue at a canteen is a useful picture. concatMap is one counter serving in order. mergeMap is many counters open. switchMap is a customer leaving the counter when a new customer comes. exhaustMap is a "counter busy" sign that turns everyone away.
The example below uses fixed delays so that the order of results is predictable: a takes 30 ms, b 20 ms, and c 10 ms.
A frequent mistake is using switchMap for saves. If the user clicks Save twice, the first request is cancelled in the browser, but the server may have already processed it. For writes prefer concatMap or exhaustMap.
typescript
import { Observable, concatMap, exhaustMap, from, lastValueFrom, map, mergeMap, switchMap, timer, toArray } from 'rxjs';
const delays: Record<string, number> = { a: 30, b: 20, c: 10 };
// Inner work: takes longer for 'a' than for 'c'.
const work = (id: string): Observable<string> =>
timer(delays[id]).pipe(map(() => `${id} done`));
const source$ = from(['a', 'b', 'c']); // all three arrive at once
console.log('switchMap ', await lastValueFrom(source$.pipe(switchMap(work), toArray())));
console.log('mergeMap ', await lastValueFrom(source$.pipe(mergeMap(work), toArray())));
console.log('concatMap ', await lastValueFrom(source$.pipe(concatMap(work), toArray())));
console.log('exhaustMap', await lastValueFrom(source$.pipe(exhaustMap(work), toArray())));
Tested with RxJS 7 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`), run twice with identical output. Results: switchMap gives only `c done`; mergeMap gives `c done`, `b done`, `a done`; concatMap gives `a done`, `b done`, `c done`; exhaustMap gives only `a done`.
Key points
`switchMap` keeps the latest, `mergeMap` runs in parallel, `concatMap` keeps order, `exhaustMap` ignores while busy.
Search and navigation: `switchMap`. Ordered writes: `concatMap`. Button spam: `exhaustMap`.
`mergeMap` accepts a concurrency limit.
Cancelling in the browser does not undo what the server already received.
Common mistakes
Using `switchMap` for save or delete calls, where cancelling is not safe.
Using `mergeMap` for typeahead, which lets an old slow response overwrite a newer one.
Nesting `subscribe` calls inside each other instead of using a flattening operator.
Follow-ups
How would you limit `mergeMap` to three requests at a time?
What happens to an HTTP call when `switchMap` cancels it?
Which operator would you choose for a form submit that can be clicked twice?
Tips
Answer with a use case for each, not only the definition.
State the save-with-switchMap trap. It is a classic senior-level point.
Use the marble or canteen picture if the interviewer wants an explanation without code.
Evaluation rubric
Defines each operator's behaviour on overlap correctly.
Matches each to a realistic use case.
Knows the cancellation limit on the server.
28.angular-0028Mediummid
How do you prevent memory leaks from subscriptions in Angular, and what are takeUntilDestroyed and DestroyRef?
A subscription to a stream that never completes keeps the callback and the component alive after the component is gone. Prevent it with the async pipe, toSignal, or takeUntilDestroyed(), which completes the stream when the component is destroyed. DestroyRef.onDestroy registers any other cleanup. Outside an injection context pass a DestroyRef explicitly.
Full answer
A memory leak here means a destroyed component cannot be garbage collected because a long-lived source still holds a reference to it through a subscription callback. The callback keeps running too, updating a screen that no longer exists.
Sources that do not complete by themselves: interval, fromEvent, Subjects, valueChanges, router events, and store selectors. HTTP calls complete after one response and are normally safe.
Ways to clean up, from best to worst:
Do not subscribe. Use the async pipe in the template or toSignal(). Both unsubscribe for you.
takeUntilDestroyed() from @angular/core/rxjs-interop. Add it as the last operator before subscribe. Called without arguments it must run in an injection context, such as a constructor or a field initializer.
Outside an injection context (inside ngOnInit or another method), inject DestroyRef as a field and pass it: takeUntilDestroyed(this.destroyRef).
Store the Subscription and call unsubscribe() in ngOnDestroy.
The older pattern is a destroy$ Subject with takeUntil(this.destroy$), which still works and appears in many code bases.
DestroyRef.onDestroy(callback) is the general tool. It runs the callback when the owner (a component, directive, or service) is destroyed. It is useful for event listeners, timers, and third-party objects.
Place takeUntilDestroyed last in the pipe, after operators such as switchMap, so no later operator can start a new inner subscription after the signal fires.
To check for leaks, use the browser's memory profiler or log in a finalize.
typescript
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, fromEvent, interval } from 'rxjs';
@Component({
selector: 'app-live-clock',
template: `
<p>Seconds on page: {{ seconds() }}</p>
<p>Window resized {{ resizes() }} times</p>
`,
})
export class LiveClockComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
readonly seconds = signal(0);
readonly resizes = signal(0);
constructor() {
// Injection context: no argument needed.
interval(1000)
.pipe(takeUntilDestroyed())
.subscribe(() => this.seconds.update((s) => s + 1));
}
ngOnInit(): void {
// Not an injection context: pass the DestroyRef explicitly.
fromEvent(window, 'resize')
.pipe(debounceTime(200), takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.resizes.update((r) => r + 1));
// Any other cleanup can be registered on the same reference.
this.destroyRef.onDestroy(() => console.log('LiveClockComponent destroyed'));
}
}
Angular 20.3 and RxJS 7. Resize the window to see the counter change, and navigate away to confirm the callbacks stop.
Key points
Long-lived sources need cleanup; HTTP usually does not.
Prefer async pipe or `toSignal`. Otherwise use `takeUntilDestroyed()`.
Outside an injection context pass `DestroyRef` to `takeUntilDestroyed`.
`DestroyRef.onDestroy` cleans up timers, listeners, and other objects.
Common mistakes
Calling `takeUntilDestroyed()` without an argument inside `ngOnInit`. It throws because there is no injection context.
Putting `takeUntil` before `switchMap`, which can leave the inner stream running.
Believing every subscription must be cleaned manually. HTTP and `take(1)` complete by themselves.
Follow-ups
Why does the async pipe not leak?
How does `takeUntilDestroyed` work inside a service?
How would you find a leak in a running app?
Tips
Start with "avoid subscribing" and only then list the cleanup tools. It shows good design thinking.
Mention `takeUntil(destroy$)` as the older pattern you can still read.
Place `takeUntilDestroyed` last in the pipe, and say why.
Evaluation rubric
Names which sources leak and which do not.
Uses takeUntilDestroyed and DestroyRef correctly.
Understands injection context rules.
29.angular-0029Mediummid
How does the @defer block work, including its triggers and the placeholder, loading and error blocks?
@defer loads a part of a template, and the code of the components inside it, only when a trigger fires. Triggers include on viewport, on idle, on interaction, on hover, on timer, and when with a condition. The @placeholder, @loading, and @error blocks cover the states before, during, and after a failed download.
Full answer
@defer is a template block that splits the components it contains into a separate JavaScript chunk and loads it later. It gives you lazy loading inside a page, not only between routes.
Syntax and states:
@defer (trigger) { ... } is the main content, shown when loaded.
@placeholder (minimum 500ms) { ... } is shown before loading starts. minimum avoids a flash if loading is quick.
@loading (after 100ms; minimum 1s) { ... } is shown while the chunk downloads. after waits before showing it, so fast loads show no spinner.
@error { ... } is shown if the download fails.
Triggers:
on idle (the default): when the browser is idle.
on viewport: when the placeholder (or a named element) scrolls into view.
on interaction and on hover: when the user clicks or hovers over an element.
on immediate: start loading right away, after the first render.
on timer(5s): after a delay.
when expression: when a condition becomes true. It fires once. Later changes to the condition do not unload the content.
prefetch on idle downloads the code early but shows it only when the main trigger fires.
Rules: only standalone components, directives, and pipes can be deferred. They must not be used anywhere else in the same file outside @defer blocks, for example in another part of the template or as a viewChild type. If they are, they stay in the main bundle. Deferred content is skipped on the server, where only the placeholder renders, unless you use the incremental hydration feature.
Good for: charts, comment sections, maps, and anything below the fold. Do not defer content that shows in the first screen, as it can hurt Largest Contentful Paint and layout stability.
typescript
// file: heavy-chart.component.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-heavy-chart',
template: `<p>Chart with {{ points().length }} points</p>`,
})
export class HeavyChartComponent {
points = input.required<number[]>();
}
// file: dashboard.component.ts
import { Component, signal } from '@angular/core';
import { HeavyChartComponent } from './heavy-chart.component';
@Component({
selector: 'app-dashboard',
imports: [HeavyChartComponent],
template: `
<h1>Dashboard</h1>
@defer (on viewport; prefetch on idle) {
<app-heavy-chart [points]="marks()" />
} @placeholder (minimum 300ms) {
<div style="height: 200px">Chart appears when you scroll here</div>
} @loading (after 100ms; minimum 500ms) {
<p>Loading chart...</p>
} @error {
<p>The chart could not be loaded.</p>
}
<button #more>Show second chart</button>
@defer (on interaction(more)) {
<app-heavy-chart [points]="[1, 2, 3]" />
} @placeholder {
<p>Press the button above.</p>
}
`,
})
export class DashboardComponent {
readonly marks = signal([55, 62, 71, 80, 77]);
}
Angular 20.3. The chart component is a stand-in for something heavy. Add a real charting library inside it.
Key points
`@defer` creates a lazy chunk for the components inside it.
Triggers: `idle`, `viewport`, `interaction`, `hover`, `immediate`, `timer`, and `when`.
`@placeholder`, `@loading`, `@error` handle the visible states. `minimum` and `after` avoid flicker.
A component also used outside the block stays in the main bundle.
Common mistakes
Deferring content that is in the first viewport, which delays it and shifts the layout.
Using `on viewport` with a placeholder that has several root elements. A trigger needs a single element.
Expecting `when` to hide the content again if the condition becomes false.
Follow-ups
What renders on the server for a `@defer` block?
How does `prefetch` differ from the main trigger?
How would you check that the chart really lives in a separate chunk?
Tips
Say that you verify with the build output and the network panel.
Mention layout shift: give the placeholder the same size as the final content.
Explain the "also used elsewhere" trap in one sentence.
Evaluation rubric
Names the main triggers and the three state blocks.
Understands what is deferred and the restrictions.
Considers performance trade-offs.
30.angular-0030Mediummid
How does content projection work with ng-content, and what are ng-container and ng-template used for?
ng-content lets a parent place its own markup inside a child component, optionally into named slots with a select attribute. ng-container groups elements without adding a DOM node. ng-template defines markup that is not rendered until something, such as ngTemplateOutlet, instantiates it, often with a context object.
Full answer
Content projection is how a reusable component accepts markup from its user, like a card whose header and body are written by whoever uses it.
<ng-content /> in the child's template marks where the projected content goes. With several slots, add select: <ng-content select="[card-title]" /> receives only elements that have the card-title attribute. The selector can be a tag, a class, or an attribute. Content that matches no slot goes to the plain <ng-content />, if there is one. Projected content is created by the parent, so its bindings use the parent's data, and it exists even if the child never shows it.
<ng-container> is an invisible grouping element. It exists in the template but renders no DOM node. Use it to apply a control-flow block or a directive to several siblings without an extra div.
<ng-template> holds markup that is not rendered by default. Something must instantiate it. ngTemplateOutlet does this: <ng-container [ngTemplateOutlet]="tpl" [ngTemplateOutletContext]="{ $implicit: item, index: i }" />. The template reads the context with let-item and let-i="index".
This is the way to let a parent customise how each row is drawn: the list component loops over data and the parent supplies the row template, found by the child through contentChild.
Legacy note: older code uses *ngIf="cond; else other" with ng-template. With the new @if/@else this is not needed, but ng-template is still very much current for outlets and custom structural directives.
Angular 20.3, strict template checks pass. The parent supplies one `ng-template` named `row`, which the list repeats for each item.
Key points
`<ng-content select="...">` creates named slots for projected content.
`ng-container` groups without a DOM node. `ng-template` is not rendered until instantiated.
`ngTemplateOutlet` plus a context object lets a parent control how items render.
`contentChild` lets the child find the template the parent passed in.
Common mistakes
Putting `<ng-content>` inside an `@if` and assuming the projected component is not created when the condition is false. The parent still creates it. Only its display is skipped.
Using `ng-template` and wondering why nothing shows. It needs an outlet or a directive.
Wrapping everything in extra `div` elements instead of `ng-container`, which breaks CSS layouts.
Follow-ups
What is the difference between `contentChild` and `viewChild`?
Who owns the change detection of projected content?
How can a component project the same content in two places?
Tips
Use a card with a title slot. Everyone understands it quickly.
Know the template context terms `$implicit` and `let-name="key"`.
Mention that `ngTemplateOutlet` is still the right tool even after control flow replaced `*ngIf`.
Evaluation rubric
Uses ng-content with select.
Explains ng-container and ng-template roles.
Uses ngTemplateOutlet with context.
31.angular-0031Mediummid
What are host directives in Angular, and how do they help you compose behaviour?
hostDirectives lets a component or directive attach other standalone directives to its own host element, and choose which of their inputs and outputs to expose. It is composition instead of inheritance, so shared behaviour such as highlighting or tooltips can be reused without extending classes or repeating attributes in templates.
Full answer
Sometimes a component always needs the same extra behaviours on its root element: a tooltip, a focus ring, tracking of clicks. Before Angular 15 you either made a base class and used inheritance, or asked every user of the component to add the attributes in the template. Both were fragile.
hostDirectives fixes this. In the decorator of a component (or another directive) you list standalone directives. Angular applies them to the host element every time the component is created, as if the user had written them.
By default none of the host directive's inputs and outputs are exposed. You choose which are public with inputs and outputs, and you can rename them with 'internalName: publicName'. The directive's lifecycle and host bindings work normally, and the order of execution is the host directives first, then the component or directive that declares them.
Rules and limits: host directives must be standalone, and a host directive cannot add elements, only behaviour on the host element.
Comparison. Inheritance (extends Base) shares code between classes but only one base is allowed and it is tied together at compile time. Composition with host directives lets you mix several small behaviours and keeps each one testable on its own. This is why design-system libraries use them.
Angular 20.3, strict template check passes. Use as `<app-chip color="gold" hint="Top scorer">Asha</app-chip>`.
Key points
`hostDirectives` applies standalone directives to the host element of a component or directive.
Expose inputs and outputs explicitly, and rename them with `'name: alias'`.
It replaces most uses of inheritance for shared behaviour.
Host directives run before the declaring class.
Common mistakes
Expecting the host directive's inputs to be public automatically. They are hidden unless listed.
Using a non-standalone directive, which is a compile error.
Duplicating the same directive in the template and in `hostDirectives`.
Follow-ups
How does this compare with extending a base class?
Can a host directive have its own host directives?
How would you expose an output from a host directive?
Tips
Contrast it with inheritance in one sentence. It is the point of the feature.
Name a real use: tooltip, focus management, analytics tracking in a design system.
If you have not used it, say so and explain what problem it solves.
Evaluation rubric
Explains what host directives are and how they are listed.
Knows inputs and outputs must be exposed.
Compares with inheritance.
32.angular-0032Mediummid
How do you unit test an Angular component with TestBed, including signal inputs and a faked service?
Configure TestBed with the standalone component in imports and fakes in providers, create the fixture, set inputs with fixture.componentRef.setInput, run change detection, and assert on the rendered DOM. Replace real services with simple fake objects so the test checks one unit.
Full answer
TestBed builds a small Angular environment around the component for a test. The usual steps:
TestBed.configureTestingModule({ imports: [MyComponent], providers: [...] }). A standalone component goes in imports, not declarations.
TestBed.createComponent(MyComponent) returns a ComponentFixture with componentInstance and nativeElement.
Set inputs through fixture.componentRef.setInput('name', value). This works for signal inputs and decorator inputs, and it marks the view for checking, which matters for OnPush components.
Run fixture.detectChanges() (or await fixture.whenStable()), then check fixture.nativeElement.
Faking dependencies. Provide a replacement with { provide: AttendanceService, useValue: fake } or useClass. A fake can be a small object, so the test does not depend on HTTP. For HTTP code use provideHttpClient() with provideHttpClientTesting() and the HttpTestingController.
Good practice:
Test behaviour seen by the user (text, enabled buttons, emitted events), not private fields.
Query by role or a stable attribute, not by deep CSS paths. Angular's CDK offers component harnesses for this.
Prefer one assertion topic per test, and name tests as sentences.
Do not call detectChanges inside loops. Trigger events with button.click() and then detect.
The Angular 20 CLI generates Jasmine and Karma tests by default. Jest and Vitest can be used instead, and experimental Vitest support was added to the CLI. Zoneless components are tested with the same API.
Run the tests with ng test.
typescript
import { Component, Injectable, computed, inject, input } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
@Injectable({ providedIn: 'root' })
export class PolicyService {
minimumPercent(): number {
return 75;
}
}
@Component({
selector: 'app-attendance-badge',
template: `<span class="badge">{{ label() }}</span>`,
})
export class AttendanceBadgeComponent {
percent = input.required<number>();
private readonly policy = inject(PolicyService);
label = computed(() => (this.percent() >= this.policy.minimumPercent() ? 'Eligible' : 'Short'));
}
describe('AttendanceBadgeComponent', () => {
let fixture: ComponentFixture<AttendanceBadgeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AttendanceBadgeComponent],
providers: [{ provide: PolicyService, useValue: { minimumPercent: () => 80 } }],
}).compileComponents();
fixture = TestBed.createComponent(AttendanceBadgeComponent);
});
it('shows Eligible when attendance meets the policy', () => {
fixture.componentRef.setInput('percent', 85);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.badge').textContent).toBe('Eligible');
});
it('uses the faked policy limit of 80 rather than the real 75', () => {
fixture.componentRef.setInput('percent', 78);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.badge').textContent).toBe('Short');
});
});
Angular 20.3 with Jasmine. Type-checked in strict mode and run with `ng test` (Karma, headless Chrome): both specs pass.
Key points
Standalone components go in `imports`. Fakes go in `providers`.
`fixture.componentRef.setInput` sets signal inputs correctly.
Call `fixture.detectChanges()` after changing data, then assert on the DOM.
Fake the service with `useValue`. Use `provideHttpClientTesting` for HTTP.
Common mistakes
Setting `fixture.componentInstance.percent = 80` on a signal input. It is read-only. Use `setInput`.
Forgetting `detectChanges()` and asserting on an empty DOM.
Testing private implementation details, which makes tests fail after harmless refactors.
Follow-ups
How do you test an `output()` event?
What does `await fixture.whenStable()` wait for?
How would you test an OnPush component that is updated by a signal?
Tips
Show `setInput`. It shows you know how signal inputs differ from the older style.
Say what you fake and why. A test should not depend on the network.
Mention that CDK harnesses make tests resilient to template changes.
Evaluation rubric
Configures TestBed correctly for a standalone component.
Uses setInput and detectChanges.
Fakes dependencies properly.
33.angular-0033Mediummid
What is a route resolver, how does a functional ResolveFn deliver data to a component, and what are the trade-offs?
A resolver is a function that loads data before the router activates a route. The result is stored under a key in the route's resolve map and, with withComponentInputBinding, arrives as a component input of the same name. The trade-off is that navigation waits for the data, so slow resolvers make the app feel stuck.
Full answer
A resolver runs during navigation, after guards and before the component is created. The router waits until it finishes. The component then starts with its data ready, so you avoid a half-empty screen and do not need loading flags inside the component.
A functional resolver is typed as ResolveFn<T> and can use inject():
It is attached in the route: resolve: { course: courseResolver }. With provideRouter(routes, withComponentInputBinding()) the component simply declares course = input.required<Course>(). The older way reads ActivatedRoute.data. The same mechanism can compute a page title: title: courseTitleResolver.
Handling failure. If the resolver's Observable errors, the navigation is cancelled and the user stays where they were, which looks like a dead link. Catch the error and return a fallback value, or return a RedirectCommand (available from Angular 18.2), which tells the router to go to another URL instead: new RedirectCommand(router.parseUrl('/not-found')).
Trade-offs:
Pro: the page renders in one piece, and the data is guaranteed in the component.
Con: there is no visible feedback during the wait unless you show a global loading bar using router events.
Con: data loading blocks the whole navigation, even if the page could show its header immediately.
Many teams load the critical data in a resolver and load secondary data inside the component with a loading state. If you want instant navigation with skeleton placeholders, skip resolvers and load in the component.
Class-based resolvers (implements Resolve<T>) are legacy.
Angular 20.3. The service returns fixed data with `of()` so the code is self-contained. A real one would call `HttpClient`.
Key points
Resolvers run after guards and before the component, and block navigation until done.
`resolve: { key: fn }` plus `withComponentInputBinding()` gives an input named `key`.
A failed resolver cancels the navigation. Catch errors and return a fallback or a `RedirectCommand`.
Choose resolvers for critical data and component-level loading for the rest.
Common mistakes
Not catching errors, so a failed request silently leaves the user on the previous page.
Resolving many slow calls and blocking the whole navigation.
Reading `route.snapshot` data inside a component that is reused for different ids, and missing updates.
Follow-ups
When would you choose a resolver instead of loading in the component?
How would you show a loading bar while a resolver runs?
How does resolver data refresh when only the route parameter changes?
Tips
Give your decision rule: critical, small data in a resolver; large or optional data in the component.
Mention the failure case. It is where most candidates stop.
Say that class-based resolvers are legacy.
Evaluation rubric
Writes a ResolveFn and attaches it to a route.
Knows how data reaches the component.
Explains trade-offs and failures.
34.angular-0034Mediummid
How do you build a custom form control that works with ngModel and reactive forms using ControlValueAccessor?
Implement ControlValueAccessor on the component (writeValue, registerOnChange, registerOnTouched, optional setDisabledState) and provide it with NG_VALUE_ACCESSOR using forwardRef and multi. The forms API then treats the component like a native input, with validators, touched state and disabled state all working.
Full answer
Angular forms talk to native inputs through built-in value accessors. A custom control, such as a star rating or a date picker, needs to speak the same protocol. ControlValueAccessor (CVA) is that bridge, with four methods:
writeValue(value): the forms API pushes a value into the component, for example from setValue or the initial value.
registerOnChange(fn): store fn and call it when the user changes the value inside the component.
registerOnTouched(fn): store fn and call it when the user leaves the control, so touched becomes true.
setDisabledState(isDisabled): optional. Called when the control is disabled or enabled.
Then register the component as an accessor: providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RatingInputComponent), multi: true }]. multi is needed because there are many accessors on the page. Use useExisting with forwardRef, since the class is referenced inside its own decorator before it is defined.
After that, <app-rating-input formControlName="rating" /> or [(ngModel)] works. Validators such as Validators.min(3) on the control apply to the value your component writes.
Signals make the internal state tidy: a signal for the value and one for the disabled state, and the template reads both.
Important: do not call onChange from writeValue. That is the form pushing a value in, and calling back creates a loop and marks the control dirty.
Signal-based forms are being developed in newer Angular versions, but CVA remains the stable, supported way in Angular 19 and 20.
Angular 20.3, strict template check passes. Use `<app-rating-input formControlName="rating" />` inside a reactive form.
Key points
Implement `writeValue`, `registerOnChange`, `registerOnTouched`, and `setDisabledState`.
Provide `NG_VALUE_ACCESSOR` with `useExisting: forwardRef(...)` and `multi: true`.
Call the stored `onChange` when the user changes the value, and `onTouched` on blur.
Do not call `onChange` inside `writeValue`.
Common mistakes
Forgetting `multi: true`, which replaces the built-in accessors.
Calling `onChange` from `writeValue`, creating loops and wrong dirty state.
Not handling `setDisabledState`, so a disabled form still lets users click.
Follow-ups
Why `useExisting` and `forwardRef` instead of `useClass`?
How would you add validation inside the custom control?
How do you make the control work with `ngModel` as well?
Tips
Walk through the data direction of each method: in, out, touched, disabled.
Explain the `forwardRef` reason briefly. It is a common follow-up.
Mention accessibility: buttons need labels and keyboard support.
Evaluation rubric
Implements all four methods correctly.
Registers the provider properly.
Avoids the writeValue loop.
35.angular-0035Hardsenior
What is zoneless change detection in Angular, how do you enable it, and what must you change in your code?
Zoneless Angular runs change detection only when Angular is told something changed, instead of after every async task patched by zone.js. Enable it with provideZonelessChangeDetection() and remove zone.js. Updates are triggered by signals read in templates, the async pipe, template events, markForCheck, and setInput, so state held in plain fields must move to signals.
Full answer
Zone.js patches browser APIs such as setTimeout, promises, and events. After each patched task, Angular runs change detection over the app. It works without effort, but it adds tens of kilobytes to the bundle, makes stack traces harder to read, and runs checks when nothing visible changed.
Zoneless mode removes zone.js. Angular then needs explicit notifications that a view might be stale. It schedules change detection when:
a signal read in a template changes;
a template or host event listener runs;
the async pipe receives a value;
ChangeDetectorRef.markForCheck() is called;
ComponentRef.setInput() is called, or a view is attached, or removed.
It does not schedule it when a plain field changes inside a setTimeout, a promise callback, or a third-party library callback. This is the migration cost: the code that "worked by accident" under zone.js stops updating. Fix it by storing the state in a signal.
Enabling: add provideZonelessChangeDetection() to the application config, and remove zone.js from the polyfills array in angular.json (and from the test builder). Status: introduced as experimental in Angular 18, developer preview in 20.0, and stable from 20.2. New CLI projects can be created with a zoneless option.
Preparing an existing app: switch components to OnPush (a component that works with OnPush mostly works zoneless), use signals for state, avoid NgZone.onStable and NgZone.run for logic (they do nothing useful), and test with the zoneless provider in TestBed. A stricter way to find problems is to run with provideZoneChangeDetection() plus the hybrid scheduler, then remove zone.js once everything passes.
Benefits: smaller bundles, faster start-up, fewer checks, and predictable debugging. It also matters for server rendering, where zone.js is awkward.
typescript
// file: main.ts
import { provideZonelessChangeDetection } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { ScoreboardComponent } from './scoreboard.component';
bootstrapApplication(ScoreboardComponent, {
providers: [provideZonelessChangeDetection()],
}).catch((err) => console.error(err));
// file: scoreboard.component.ts
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-scoreboard',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Plain field: {{ plainRuns }}</p>
<p>Signal: {{ runs() }}</p>
<button (click)="later()">Update after 1 second</button>
`,
})
export class ScoreboardComponent {
plainRuns = 0; // Changed in a timer: the view is NOT refreshed in zoneless mode.
readonly runs = signal(0); // Read in the template: the view IS refreshed.
later(): void {
setTimeout(() => {
this.plainRuns++;
this.runs.update((n) => n + 1);
}, 1000);
}
}
Angular 20.3. In `angular.json` remove `zone.js` from `polyfills`. The first button in the example does not update the screen in zoneless mode, the second does.
Key points
Zoneless removes zone.js and relies on explicit change notifications.
Triggers: signals in templates, template events, `async` pipe, `markForCheck`, `setInput`.
Plain fields changed in timers or promises no longer update the view. Use signals.
Stable from Angular 20.2. Enable with `provideZonelessChangeDetection()` and drop zone.js from polyfills.
Common mistakes
Removing zone.js but leaving mutable fields updated in `setTimeout` callbacks, so the screen freezes.
Depending on `NgZone.onStable` or `NgZone.run` in application logic.
Forgetting to remove zone.js from the test setup, so tests still run in a zone and hide bugs.
Follow-ups
How would you migrate a large app step by step?
How does a third-party library that relies on zone.js behave?
Why does OnPush readiness predict zoneless readiness?
Tips
Start with what zone.js does and what it costs. Then explain what replaces it.
Give the exact failure example: a plain field set in `setTimeout`.
State the status correctly (stable from 20.2). A wrong status is a quick way to lose trust.
Evaluation rubric
Explains zone.js role and zoneless triggers.
Identifies the plain-field pitfall.
Gives a realistic migration plan and correct status.
36.angular-0036Hardsenior
How do server-side rendering and hydration work in Angular, and what are the common causes of hydration problems?
With SSR the server renders the component tree to HTML, so users and crawlers see content before JavaScript runs. Hydration then reuses that DOM in the browser instead of rebuilding it, attaching listeners and state. Problems come from code that touches browser-only APIs on the server or changes the DOM outside Angular, which creates mismatches.
Full answer
In a client-only app the browser downloads JavaScript, runs it, then builds the page. With server-side rendering (SSR) the server runs the same Angular code and sends finished HTML. The page shows content early (better Largest Contentful Paint) and search engines see real content. Static prerendering (SSG) does the same at build time for pages that rarely change.
Without hydration the browser would destroy that HTML and render again, which flashes and wastes work. With provideClientHydration() Angular walks the existing DOM, matches it against the component tree, and reuses the nodes. It also restores state sent by the server. withEventReplay() records user clicks made before hydration finishes and replays them afterwards.
The server also uses HttpClient. With hydration enabled, GET responses are cached and transferred to the browser in the page, so the browser does not repeat the same calls on start-up. TransferState does the same for your own data.
In Angular 19 and 20 you choose how each route renders with ServerRoute definitions: RenderMode.Prerender, RenderMode.Server, or RenderMode.Client.
What goes wrong:
Using window, document, or localStorage directly. These do not exist on the server. Use afterNextRender, isPlatformBrowser, or inject DOCUMENT.
Changing the DOM by hand (innerHTML, jQuery-style code, some third-party widgets). The server and client DOM differ, so Angular raises a hydration mismatch error (NG0500 series). Opt such a component out with ngSkipHydration.
Invalid HTML nesting, such as a div inside a p, which the browser repairs differently from the server output.
Values that differ per environment, such as Date.now() or random numbers, rendered into the template.
Check by opening the browser console in development mode, which logs hydration mismatches and shows the first differing node.
typescript
// file: app.config.ts
import { provideHttpClient, withFetch } from '@angular/common/http';
import { ApplicationConfig } from '@angular/core';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient(withFetch()), provideClientHydration(withEventReplay())],
};
// file: app.routes.server.ts
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{ path: '', renderMode: RenderMode.Prerender },
{ path: 'account', renderMode: RenderMode.Client },
{ path: '**', renderMode: RenderMode.Server },
];
// file: saved-theme.component.ts
import { Component, afterNextRender, signal } from '@angular/core';
@Component({
selector: 'app-saved-theme',
template: `<p>Theme: {{ theme() }}</p>`,
})
export class SavedThemeComponent {
readonly theme = signal('light'); // Same value on server and client at first render.
constructor() {
// Runs only in the browser, after the first render, so localStorage is safe.
afterNextRender(() => {
this.theme.set(localStorage.getItem('theme') ?? 'light');
});
}
}
Angular 20.3 with @angular/ssr 20. In a CLI project the server entry files (`main.server.ts`, `server.ts`) are generated by `ng add @angular/ssr`. The code shown is the part you write yourself.
Key points
SSR sends HTML for fast first paint and SEO. Hydration reuses that DOM instead of rebuilding it.
Enable with `provideClientHydration(withEventReplay())` and the SSR build setup (`ng add @angular/ssr`).
Browser-only code goes in `afterNextRender` or behind `isPlatformBrowser`.
Manual DOM changes and invalid HTML are the usual mismatch causes.
Common mistakes
Reading `window.innerWidth` in a constructor, which crashes on the server.
Rendering `new Date()` or random values in the template, so server and client text differ.
Treating SSR as a pure performance feature. It adds server cost and complexity, and often only SEO or first paint justify it.
Follow-ups
How does the HTTP transfer cache avoid duplicate requests?
When would you choose prerendering over per-request SSR?
How would you debug an NG0500 mismatch error?
Tips
Describe the full path: server HTML, then hydrate, then event replay. Candidates who stop at "SSR is good for SEO" sound junior.
Mention how you keep browser-only code out of the server path.
Be honest about costs: server hosting, cache strategy, and extra debugging.
Evaluation rubric
Explains hydration versus re-rendering.
Lists realistic mismatch causes with fixes.
Knows render modes and the HTTP transfer cache.
37.angular-0037Hardsenior
What is incremental hydration, and how do the hydrate triggers on @defer blocks work?
Incremental hydration lets the server render the whole page but the browser hydrate selected @defer blocks only when a hydrate trigger fires, such as viewport, interaction, or hover. Until then the block stays as static server HTML and its JavaScript is not downloaded, so less script runs at start-up.
Full answer
Normal hydration wakes up the entire page when the application starts. On a long page with comments, a footer, and a recommendation list, most of that work is wasted for a user who only reads the top.
Incremental hydration (stable in Angular 20) hydrates parts of the page later. You enable it with provideClientHydration(withIncrementalHydration()) and mark deferrable blocks with hydrate triggers:
html
@defer (hydrate on viewport) { <app-comments /> }
What happens: on the server the block renders its real content (not the placeholder, which is what a plain @defer does on the server). In the browser Angular leaves that HTML untouched and does not load the component code. When the trigger fires, it downloads the chunk and hydrates the existing DOM. Clicks before that are captured and replayed, because incremental hydration uses event replay.
Hydrate triggers: hydrate on idle, on viewport, on interaction, on hover, on immediate, on timer(ms), hydrate when condition, and hydrate never (the block stays static HTML forever, which suits content with no interactivity).
You can combine hydrate triggers with normal triggers: @defer (on viewport; hydrate on interaction).
Rules to know: the parent block hydrates before its children. Content must be deterministic between server and client. Blocks are only dehydrated when the page was server-rendered. In a client-only run the block behaves like an ordinary @defer.
Trade-off: it lowers JavaScript at start-up (better Interaction to Next Paint and Total Blocking Time), but the first interaction with a dehydrated block waits for download and hydration. Keep primary actions (add to cart) hydrated early, and defer decorative or below-the-fold parts.
typescript
// file: app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideClientHydration, withIncrementalHydration } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [provideClientHydration(withIncrementalHydration())],
};
// file: comments.component.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-comments',
template: `
<button (click)="like()">Like ({{ likes() }})</button>
`,
})
export class CommentsComponent {
readonly likes = signal(0);
like(): void {
this.likes.update((n) => n + 1);
}
}
// file: article.component.ts
import { Component, signal } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-article',
imports: [CommentsComponent],
template: `
<article>
<h1>How exams are scheduled</h1>
<p>Static text that never needs JavaScript.</p>
</article>
@defer (on viewport; hydrate on interaction) {
<app-comments />
} @placeholder {
<p>Comments</p>
}
@defer (hydrate when showFooterTools()) {
<app-comments />
}
@defer (hydrate never) {
<footer>Copyright notice (static text only)</footer>
}
`,
})
export class ArticleComponent {
readonly showFooterTools = signal(false);
}
Angular 20.3. Needs the SSR setup from `ng add @angular/ssr`. The comments component is a stand-in.
Key points
Enable with `withIncrementalHydration()`. Mark blocks with `@defer (hydrate on ...)`.
The server renders the real content; the browser hydrates it only when the trigger fires.
Triggers include `idle`, `viewport`, `interaction`, `hover`, `immediate`, `timer`, `when`, and `never`.
Parents hydrate before children. Early user events are replayed.
Common mistakes
Using `hydrate never` on a block that has buttons or forms, so it never becomes interactive.
Deferring the main call-to-action, which delays the first meaningful interaction.
Expecting it to work without SSR. Without a server render there is nothing to keep dehydrated.
Follow-ups
How is this different from the plain `@defer` placeholder behaviour on the server?
What happens to a click inside a dehydrated block?
How would you decide which blocks to hydrate on viewport?
Tips
Contrast it with full hydration and name the metric it improves (start-up JavaScript, INP, TBT).
Mention the trade-off. Senior answers always include one.
Say it needs SSR and event replay.
Evaluation rubric
Understands dehydrated versus hydrated blocks.
Lists hydrate triggers and combinations.
Weighs the trade-offs.
38.angular-0038Hardsenior
How do you find and fix performance problems in a large Angular application?
Measure first with Lighthouse, the browser Performance panel, Angular DevTools, and a bundle analysis, then fix the biggest cost. Typical fixes are lazy loading and @defer for bundle size, OnPush with signals and stable track keys for runtime, NgOptimizedImage and SSR for loading, and virtual scrolling for very long lists.
Full answer
Start with a metric and a measurement, not with a favourite trick. Which problem is it: slow first load, slow interaction, or slow scrolling and updates?
Analyse the bundle. ng build --stats-json and an esbuild bundle analyser show what is large. Set budgets in angular.json so a build fails when the initial bundle grows.
Lazy load routes (loadComponent, loadChildren) and defer heavy parts of a page with @defer.
Replace large libraries (for example a full date library) with smaller ones, or import only what is needed.
Use NgOptimizedImage: it enforces width and height, lazy loads images, and the priority attribute marks the LCP image with a preload hint.
Consider SSR or prerendering for first paint and SEO.
Adding OnPush everywhere before measuring, and then fixing stale-view bugs for no gain.
Calling a sorting or filtering function in the template, which runs on every check.
Lazy loading everything, including tiny components, which adds requests and delays.
Follow-ups
How would you set a performance budget and enforce it in CI?
How do you find which component is slow in Angular DevTools?
What is the effect of `priority` on `NgOptimizedImage`?
Tips
Begin with the measurement method. This is what separates senior answers from lists of tricks.
Tie every fix to a metric (LCP, INP, bundle size).
Say what you would not optimise.
Evaluation rubric
Starts with measurement and a target.
Separates loading and runtime problems.
Gives specific Angular tools and trade-offs.
39.angular-0039Hardsenior
How would you design state management with signals and services, and when would you choose NgRx instead?
A signal store is a service that keeps state in private writable signals, exposes read-only signals and computed values, and changes state only through named methods with immutable updates. It is enough for most apps. NgRx adds actions, reducers, effects, and tooling, which pay off for large teams, complex side-effect flows, and the need to inspect and replay changes.
Full answer
State management means deciding where data lives, who can change it, and how others find out. Start with the smallest tool that works.
Levels:
Local component state: a signal in the component.
Shared feature state: a service with signals, provided at root or at feature route level.
A state library: NgRx (Store, or the lighter NgRx SignalStore), or another library.
A signal store service follows a few rules:
State is held in a private WritableSignal. Outside code gets asReadonly() or computed views, so it cannot change state directly.
Changes happen through methods named after intent (addItem, clear), which use update with a new object or array, never in-place mutation.
Derived values (totals, counts, filtered lists) are computed, not stored copies.
Side effects (HTTP, storage) are done in the methods or in an effect, and results flow back as state.
Loading and error states are part of the state, so templates can show them.
When to move to NgRx: many teams share one large state, features need strict conventions, you must trace "which action caused this", you need time-travel debugging, undo, or complex orchestration of side effects (cancellation, debouncing, retries), or multiple features react to the same events. The cost is more files and indirection. NgRx SignalStore is a middle path: signals with structure and plugins, with less boilerplate than the classic Store.
Server state (data that lives on the backend) is a separate topic. A cache of fetched data needs invalidation and refetching. Do not copy it into global state without a reason.
Interview tip: say that the choice depends on team size and complexity, and show the simple option first.
Angular 20.3, strict template check passes. Provide the store in a feature route with `providers: [CartStore]` to scope it, or keep `providedIn: 'root'` for app-wide state.
Key points
Private writable signal, public read-only views, change through intent-named methods.
Immutable updates and `computed` for derived values.
Keep loading and error flags in state.
NgRx fits large teams, traceability, and complex side-effect orchestration.
Common mistakes
Exposing the writable signal, so any component can change state in unplanned ways.
Storing derived data (such as a total) as a separate signal that can go out of sync.
Using a global store for state that belongs to one component.
Follow-ups
What is the difference between NgRx Store and NgRx SignalStore?
How would you handle optimistic updates and rollback?
Where would you keep server cache data?
Tips
Show the small solution first and name the point where you would move to NgRx.
Mention immutability, since it also keeps OnPush correct.
Say that you treat server data differently from UI state.
Evaluation rubric
Designs a clean signal service.
Gives concrete criteria for choosing NgRx.
Separates server state from client state.
40.angular-0040Hardsenior
How do signals work internally, including lazy computed values, memoization, equality checks, dynamic dependencies and untracked reads?
Signals form a dependency graph. A write marks dependents as possibly stale but does not recompute them (push). A read recomputes only what is actually stale (pull), and a computed whose new value equals the old one stops the change from spreading. Dependencies are recorded on each run, so they can change from run to run.
Full answer
Think of a signal as a node with a version number. A computed or an effect is a consumer. While a consumer runs, every signal it reads registers it as a dependency. This record is rebuilt on every run, so dependencies are dynamic: flag() ? a() : b() depends on b only while flag is false.
Writing a signal does two things. It bumps the version and walks its consumers, marking them dirty. It does not run any user code at this point. Reading a computed then checks whether it is dirty. If it is, it first checks whether any of its producers really changed (by version), and only re-runs the function when one did. This push of dirtiness plus pull of values is why computeds are lazy, cached, and glitch-free: a value that depends on two signals is never seen half-updated, because the recompute happens on read, after all writes.
Equality cuts the graph. If a computed recalculates and the new value is equal to the old (default check: Object.is), its version does not change, so its own consumers do not recalculate. In the example isEven is derived from a counter. A downstream label recomputes only when parity changes, not on every increment. You can supply a custom equal function in signal or computed options, for example to compare objects by id.
untracked(() => ...) reads signals without registering dependencies.
Rules and errors: a computed must be pure. Writing to a signal inside a computed throws an error (NG0600). Reading a signal that is currently being computed in a cycle throws too. Effects are scheduled asynchronously by Angular and run when the framework flushes them.
Consequences for design: keep computeds cheap and side-effect free, do not store derived data twice, and do not mutate objects held in signals (the default equality would see no change).
The script runs without a browser. It prints how many times each function really ran.
Tested with Angular 20.3 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`), twice with identical output. Run counts printed by the script are the point of the example.
Key points
Writes mark dependents dirty (push). Reads recompute stale values (pull). Nothing runs on write.
Dependencies are tracked on every run, so they can change dynamically.
A recomputed value equal to the old one stops propagation. Custom `equal` is possible.
Computed must be pure. Writing a signal in a computed throws NG0600.
Common mistakes
Putting a side effect inside `computed` and being surprised that it runs rarely, or not at all.
Mutating an object in a signal and expecting a change notification.
Assuming a computed re-runs on every `set` of its source. It runs lazily and only if the source really changed.
Follow-ups
What does glitch-free mean, and how does the pull model provide it?
How does a computed avoid recalculating when its source is set to the same value?
What happens if a computed reads itself?
Tips
Use the run counters from the script to explain laziness. A visible number is more convincing than a definition.
Mention versioning and equality, since they explain why the model is fast.
Connect the theory to a design rule: pure computeds, immutable values.
Evaluation rubric
Explains push dirtiness and pull evaluation.
Understands dynamic dependencies and equality cutting.