Questions 161–180 of 195 · 0 of 20 on this page marked learned
161.angular-0161Easyfresher
What does "NullInjectorError: No provider for X" mean, what are the usual causes, and how do you fix it in an app and in a test?
It means the injector looked for a provider for a token and found none. Older versions print `NullInjectorError: No provider for X!`, and Angular 20 prints `NG0201: No provider found for X`. Typical causes: a service without providedIn or providers, HttpClient used without provideHttpClient(), Router or other framework services missing in a test, or a service provided in a place that the component cannot reach. Provide the token where the consumer can see it.
Full answer
Dependency injection works like this: a class asks for a token (usually a class such as HttpClient), and the injector looks for a provider that knows how to create it. If it climbs to the top and finds nothing, it throws an error. Older versions print NullInjectorError: No provider for HttpClient!. In Angular 20 the text is NG0201: No provider found for HttpClient, followed by the source and the path of the dependency chain, such as StudentApi -> HttpClient. The name NullInjectorError is still what people search for, and the cause and the fixes are the same.
Common causes and fixes:
A service with no registration. A class marked with plain @Injectable() is not provided anywhere. Fix: @Injectable({ providedIn: 'root' }), or add it to providers of a component, route or the application config.
HttpClient without setup. In standalone apps add provideHttpClient() to the application config. Without it: No provider for HttpClient.
Router tokens (ActivatedRoute, Router) in a unit test. Add provideRouter([]) to the test providers.
Providers in the wrong place. A service listed in the providers of one component is visible to that component and its children, not to a sibling or a parent.
An InjectionToken that has no value and no default factory. Provide it, or give the token a factory.
A library service that needs a provider function, for example provideAnimations(), provideStore() for NgRx, or provideNativeDateAdapter() for Material date pickers.
How to read the error: the first line names the token. Ask "who should provide this?" and put the provider at the right level. Use { optional: true } in inject only when the dependency is truly optional.
In tests, TestBed.configureTestingModule({ providers: [...] }) is the place. Prefer the real provider function (provideHttpClient() with provideHttpClientTesting()), or supply a fake: { provide: GradeApi, useValue: fakeApi }.
Do not fix the error by providing the same service in many components, because each place creates a new instance, and shared state will no longer be shared.
typescript
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
@Injectable() // not provided anywhere
export class BrokenService {}
@Injectable({ providedIn: 'root' }) // fixed: provided at the root
export class FixedService {}
@Injectable({ providedIn: 'root' })
export class StudentApi {
private readonly http = inject(HttpClient); // needs provideHttpClient()
load(): void {
this.http.get('/api/students').subscribe();
}
}
export function reproduce(): string[] {
const out: string[] = [];
try {
TestBed.inject(BrokenService);
} catch (error) {
out.push((error as Error).message.split('\n')[0]);
}
try {
TestBed.inject(StudentApi);
} catch (error) {
out.push((error as Error).message.split('\n')[0]);
}
TestBed.resetTestingModule();
TestBed.configureTestingModule({ providers: [provideHttpClient()] });
out.push(TestBed.inject(FixedService) ? 'FixedService ok' : 'missing');
out.push(TestBed.inject(StudentApi) ? 'StudentApi ok with provideHttpClient' : 'missing');
return out;
}
Angular 20.3. A Karma test reproduces the error for an unprovided service and for HttpClient, then shows the fixed forms. The captured messages (Angular 20.3) start with `NG0201: No provider found for` and name the token, and the second one ends with the path `StudentApi -> HttpClient`.
Key points
The error means no provider exists for the requested token at the injector level that was searched.
Fix by `providedIn: 'root'`, `providers`, or a provider function such as `provideHttpClient()`.
In tests add providers in `TestBed.configureTestingModule`.
Provide at the right level. Do not copy providers everywhere.
Common mistakes
Using `@Injectable()` without `providedIn` or `providers`.
Forgetting `provideHttpClient()` or `provideRouter()` in tests.
Providing a service in a sibling component and expecting a parent to see it.
Follow-ups
What does `{ optional: true }` change?
Why is providing in several components risky?
How do you replace a real service with a fake in a test?
Tips
Read the token name in the message first.
Mention provider functions such as `provideHttpClient`.
Explain levels: root, route, component.
Evaluation rubric
Explains the lookup and the message.
Lists the usual causes with fixes.
Handles the test setup.
162.angular-0162Easyfresher
What is the difference between ng serve and ng build, and between a development build and a production build?
ng serve builds in memory, starts a dev server and reloads on changes, with source maps and no optimisation. ng build writes files to the output folder. A production build (the default configuration of ng build) turns on minification, tree shaking, hashing, and budgets, so the files are small and ready to deploy.
Full answer
Two commands you use every day:
ng serve (also ng s) is for development. It builds the app, keeps the result in memory, starts a local server (http://localhost:4200), and rebuilds when you save a file. The browser updates through live reload, and in many cases through hot module replacement, which swaps styles and templates without losing app state. It uses the development configuration: no minification, source maps on, so you can debug the original TypeScript.
ng build creates files on disk, by default in dist/<project>/browser. Since Angular 17 the default configuration is production. It is the thing you deploy.
What a production build does:
Minification: shorter variable names, no spaces, so files are small.
Tree shaking: removes code that nothing uses.
Ahead-of-time (AOT) compilation of templates, which is also used in development now.
Output hashing: file names such as main-AB12CD34.js allow long caching.
Budgets: warnings or errors when the bundle gets bigger than the limits in angular.json.
Optimised fonts and styles inlining (critical CSS), and no source maps by default.
Differences you can see: a development bundle is several times larger and has readable code. Errors in production show minified names unless you upload source maps to your error tracker.
Useful options: ng serve --open, --port 4300, --configuration production (to test a production-like build locally), ng build --configuration development (readable output), ng build --stats-json for bundle analysis, ng build --base-href /school/ for a sub path.
Never deploy the output of ng serve: it does not exist on disk, and it is not optimised. And remember that the dev server is only for your machine: it has no caching rules, no compression settings, and no server rendering behaviour that matches your production host.
Angular CLI 20.3. The `ng build` output sizes were not measured for this answer, so the answer states differences in general terms. The excerpt shows the options from the CLI generated configuration.
Key points
`ng serve` is a dev server with live reload, source maps and no optimisation.
`ng build` writes files to `dist`, and production is the default configuration.
Production does minification, tree shaking, hashing and budgets.
Test production behaviour with `--configuration production` before release.
Common mistakes
Deploying a development build and wondering why the app is slow.
Debugging performance in the dev server and trusting the numbers.
Forgetting that production errors need source maps to read.
Follow-ups
What are budgets, and where are they configured?
What does output hashing give you?
How do you serve the production build locally?
Tips
Contrast the two commands first, then the two configurations.
List at least four production optimisations.
Say that you test the production build before release.
Evaluation rubric
Separates the commands and the configurations.
Lists the optimisations correctly.
Knows options for development and deployment checks.
163.angular-0163Easyfresher
How do you use Angular DevTools to inspect components, signals and change detection when debugging an app?
Angular DevTools is a browser extension with a Components tab (tree, inputs, outputs, state, signals, and a way to edit values), a Profiler tab (records change detection passes and times), and an Injector tree view. It works with development builds, and complements console.log and the browser debugger.
Full answer
Angular DevTools is an extension for Chrome and Firefox. It adds an "Angular" tab to the browser developer tools. It works with Angular apps that run in development mode (a production build hides most information).
Tabs and what they are good for:
Components. Shows the component tree of the page. Click a component to see its inputs, outputs, and the current values of its fields, including signals (it can show the value of a signal and edit simple values). You can also jump to the component's source. Use it to answer "what data does this component really have right now?" and "which parent passes this input?".
Profiler. Record, interact with the page, then stop. It shows each change detection pass as a bar with its time, and which components were checked and how long each took. Use it to find passes that run too often (a timer or scroll listener inside the zone) or components that are slow to check. Compare before and after a fix.
Injector tree. Shows the hierarchy of injectors (element injectors, environment injectors) and the providers in each, which helps when you ask why a component gets a certain instance of a service.
Router tree (in newer versions). Shows the route configuration and the active route.
Other debugging tools to know:
The browser debugger with source maps: set breakpoints in TypeScript.
console.log and the json pipe in a template for a quick look: {{ student | json }}.
The ng global in development: ng.getComponent(element), ng.applyChanges(component).
Reading error codes (NG0100) and the docs page for each.
The Network tab for HTTP problems, and the Performance tab for slow interactions.
Habits: reproduce the problem, check data in the Components tab, check how often passes run in the Profiler, and only then change code.
typescript
import { Component, computed, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';
@Component({
selector: 'app-debug-me',
imports: [JsonPipe],
template: `
<button type="button" (click)="addMarks()">Add 5 marks</button>
<pre>{{ summary() | json }}</pre>
`,
})
export class DebugMeComponent {
readonly name = signal('Asha');
readonly marks = signal(70);
// In DevTools you can see both signals and this computed value, and edit marks.
readonly summary = computed(() => ({ name: this.name(), marks: this.marks() }));
addMarks(): void {
this.marks.update((m) => m + 5);
}
}
Angular 20.3. DevTools is a browser extension, so it was not run here. The sample is a component with a signal that you can inspect, and the `json` pipe line was type-checked.
Key points
Angular DevTools adds Components, Profiler and Injector views to the browser tools.
Components shows inputs, outputs and signal values. The Profiler shows change detection passes and timings.
It needs a development build. Use it with the browser debugger and `ng` helpers.
Reproduce, inspect data, measure passes, then fix.
Common mistakes
Trying to profile a production build and finding little data.
Guessing at performance problems without recording a profile.
Adding `console.log` in many places instead of checking the Components tab.
Follow-ups
What would you look for if the Profiler shows hundreds of passes per second?
How does the injector tree help with provider problems?
What does the `ng` global offer in development?
Tips
Name the three tabs with one use each.
Mention that it needs development mode.
Say how you combine it with the browser debugger.
Evaluation rubric
Describes the main tabs and their use.
Knows the development mode limit.
Combines DevTools with other debugging tools.
164.angular-0164Easyfresher
What does the input transform option do, and how do booleanAttribute and numberAttribute help with HTML-style attributes?
HTML attributes are strings, so <app-tab disabled> passes an empty string and <app-box size="3"> passes "3". An input transform converts the incoming value before the component sees it. booleanAttribute and numberAttribute are the built-in transforms, and you can write your own for trimming or clamping.
Full answer
When you write a plain attribute in a template, such as <app-chip disabled> or <app-box size="3">, Angular passes a string. For disabled, the value is the empty string '', which is falsy, so a naive check treats it as "not disabled". This is the problem that input transforms solve.
A transform is a function that runs when the parent sets the input. The component receives the converted value, and the type of the input is the type after conversion. You write it as input(false, { transform: booleanAttribute }).
Built-in transforms:
booleanAttribute: '' becomes true, 'true' becomes true, 'false' becomes false, undefined and null become false, and any other string becomes true. So <app-chip disabled>, <app-chip disabled="true"> and [disabled]="flag" all work.
numberAttribute: converts strings to numbers, so size="3" becomes 3. It returns NaN for text that is not a number (you can give a fallback: numberAttribute(value, 10) through a small wrapper).
Custom transforms are plain functions: trim a string, clamp a number into a range (rating between 0 and 5), or turn a comma separated string into an array. Keep them pure, fast and without side effects, because they run on every input change. They should accept the wider type the parent may pass (string | number) and return the type the component wants.
The same option exists for decorator inputs: @Input({ transform: booleanAttribute }) disabled = false;.
Why it matters: it makes your component feel like a native HTML element, and removes if (typeof x === 'string') checks inside the component. With strictTemplates, the template type is the input's accepted type, so [size]="'abc'" is still accepted as a string and becomes NaN at run time. Validate where it matters.
Do not use a transform for logic that depends on other inputs. Use computed for that.
Angular 20.3, strict template check passes. A Karma test renders the component with a bare attribute, with `"false"`, with a number string and with an out of range rating, and checks the resulting text.
Key points
Plain attributes pass strings, so `<x disabled>` gives `''`.
`transform` converts the value before the component sees it.
`booleanAttribute` and `numberAttribute` are built in. Custom transforms are pure functions.
Use `computed` for logic that depends on several inputs.
Common mistakes
Checking `if (this.disabled)` with a raw string input and treating `''` as false.
Writing transforms with side effects.
Expecting `numberAttribute` to throw on text. It gives `NaN`.
Follow-ups
How would you clamp a rating between 0 and 5?
What is the type of the input after the transform?
When would you use `computed` and not a transform?
Tips
Start with the `disabled` attribute problem.
Show both built-ins and one custom transform.
Say that transforms must be pure.
Evaluation rubric
Explains the string attribute problem.
Uses the built-in transforms correctly.
Writes and limits custom transforms.
165.angular-0165Easyfresher
What does distinctUntilChanged do, why is it used in a search box pipe, and how do you compare objects with it?
distinctUntilChanged drops a value when it equals the previous value, so equal consecutive values are ignored. In a search box it comes after debounceTime so the app does not repeat a request for the same text. For objects pass a comparator or a key selector, because the default check uses ===.
Full answer
distinctUntilChanged() remembers the last value that it let through. When a new value arrives, it compares the two. If they are equal, the new value is dropped. If not, it is emitted and becomes the new "last value".
Important: it compares only with the previous value, not with every earlier one. The sequence 1, 1, 2, 1 becomes 1, 2, 1. For a full unique list, use a Set, or the distinct() operator (which remembers everything and can leak memory on long streams).
Search box use: a user types "ang", pauses, types "x", and deletes it again. After debounceTime(300) you get "ang", "angx", "ang". Without more filtering, the app would send a request for "ang" twice in a row, and (with switchMap) cancel and restart work for the same value. A pipe that is usually written is:
The order is deliberate: debounce first to reduce the events, normalise (trim, lower case) so that "Ang " and "ang" count as equal, then drop duplicates, then call the server.
Comparing objects. By default the check is ===, so two different objects with the same content are "different". Two options:
A comparator: distinctUntilChanged((a, b) => a.id === b.id). Returning true means "same".
A key selector (the second argument): distinctUntilChanged((a, b) => a === b, user => user.id), which compares the selected keys; or distinctUntilKeyChanged('id').
Also remember NaN: the default comparison is ===, and NaN !== NaN, so repeated NaN values pass through.
With signals, computed already skips equal values (it uses Object.is), so distinctUntilChanged is mostly needed on observable pipes such as form valueChanges, route params and WebSocket streams.
RxJS 7.8. The script was run in Node 24 twice with identical output. It prints the plain numbers case, the typed text case, and the user objects with and without a comparator. The NaN statement was checked in that run.
Key points
It drops a value equal to the previous one, comparing only with the last passed value.
In search: debounce, normalise, `distinctUntilChanged`, then `switchMap`.
For objects use a comparator or a key selector, because the default is `===`.
`computed` signals already skip equal values.
Common mistakes
Using it before `debounceTime` and getting no benefit.
Expecting `1, 1, 2, 1` to become `1, 2`.
Comparing objects without a comparator.
Follow-ups
How is it different from `distinct()`?
How would you compare users by `id`?
Why do you normalise the text first?
Tips
Give the `1, 1, 2, 1` example.
State the order of operators in a search box.
Mention that `computed` handles equality for signals.
Evaluation rubric
Explains previous-value comparison.
Places it correctly in a search pipe.
Uses comparator or key selector for objects.
166.angular-0166Easyfresher
How do the RxJS creation functions of, from, interval and timer differ, and when do you use each?
of emits the values you list and completes. from converts an array, promise or iterable to an observable. interval emits increasing numbers on a repeating delay and never completes. timer waits for a delay, emits 0, and can repeat if you give a second argument. Timers keep running until you unsubscribe.
Full answer
Creation functions make an observable from something that is not an observable. You import them from rxjs (not from rxjs/operators).
of(a, b, c): emits each argument, then completes. of([1, 2]) emits one value, the array. Use it for test data, default values or returning a fixed result from a catchError.
from(source): converts an array, a string, a Set, a Promise or another iterable. from([1, 2, 3]) emits three values. from(fetchPromise) emits the resolved value once and completes. The difference with of: from spreads the input, of takes the arguments as they are.
interval(ms): emits 0, 1, 2 ... every ms milliseconds, after waiting ms for the first one. It never completes, so you must stop it with take, takeUntil, takeUntilDestroyed or unsubscribe.
timer(due): waits due ms, emits 0 and completes. timer(0, 1000) emits at once and then every second (the second argument is the period), so it is interval with an initial delay you choose. timer(5000) is a good "do this once after 5 seconds" tool.
Other useful ones: EMPTY (completes at once), NEVER, throwError(() => new Error('x')), fromEvent(button, 'click') for DOM events, defer(() => from(fetchData())) to delay creating the source until subscription (a promise starts immediately when it is created, but defer waits).
Notes:
Synchronous sources (of, from(array)) emit during subscribe, before the next line of code runs.
Timers need cleanup. In a component use takeUntilDestroyed(). A timer that is never unsubscribed keeps the app unstable, which delays server rendering and service worker registration.
interval uses setInterval, so a busy browser can delay ticks. Do not use it as a precise clock.
RxJS 7.8. The script was run in Node 24 twice with identical output. Time based values print as ordered events, and it exits when the timers are done.
Key points
`of` lists values, `from` spreads an array or converts a promise or iterable.
`interval` repeats and never completes. `timer` waits first and can repeat with a second argument.
Always stop timers with `take`, `takeUntil` or `takeUntilDestroyed`.
`defer` delays creation until subscription.
Common mistakes
Using `of([1, 2, 3])` and expecting three values.
Forgetting to stop `interval`.
Creating a promise early and thinking `from(promise)` delays it.
Follow-ups
What is the difference between `timer(0, 1000)` and `interval(1000)`?
When do you use `defer`?
Why is a timer a problem for server rendering?
Tips
Give the `of([1,2,3])` versus `from([1,2,3])` example.
Mention cleanup for timers.
Mention `defer` for promises.
Evaluation rubric
Describes the four functions correctly.
Shows the `of` versus `from` difference.
Handles cleanup and timing details.
167.angular-0167Mediummid
Compare a pure pipe, a method call and a computed signal for derived values in a template. Which runs how often, and which should you choose?
A method call in a template runs on every change detection pass. A pure pipe runs again only when its input reference changes. A computed signal runs only when a signal it read changes, and its result is cached. Prefer computed for state in the component, and a pure pipe for reusable formatting of an input value.
Full answer
Templates are evaluated often. Where you put derived logic decides how many times it runs.
Method call: {{ fullName() }} with a normal method. Angular cannot know what the method depends on, so it calls it on every check of that view. With default change detection that can be dozens of times for one click. Cheap getters are fine, but filtering a big list or formatting many rows in a method is a common cause of slow screens.
Pure pipe: {{ student | fullName }}. Angular calls transform again only when the input value (reference) changes, or an argument changes. If you mutate the object in place, the pipe does not run again. Pure pipes are reusable across templates and easy to test as classes. The cache is per pipe usage in a template, not shared globally.
Computed signal: readonly fullName = computed(() => this.first() + ' ' + this.last()). It runs when it is read and one of the signals it depends on has changed, then caches. If nothing changed, reading it again returns the cached value without running the function. It works with OnPush and zoneless apps, and dependencies are tracked automatically.
Impure pipe (pure: false): runs on every check like a method. Use it only when the pipe depends on outside state, or on a mutated array, and the work is small. The async pipe is the well-known impure pipe.
How to choose:
Value derived from component state: computed.
Formatting a value that comes from input, with logic reused in many places: a pure pipe.
A tiny expression such as a + b or a ternary: write it inline.
A method call in a template: only when it is trivial, or when it takes an event handler.
Memoizing a method by hand (storing the last argument and result) works but duplicates what pipes and computed already do.
Measure before you refactor: count calls with a counter, as in the test, or use the Angular DevTools profiler. If a method is cheap and called a few times, leave it.
Angular 20.3, strict template check passes. A Karma test counts calls. The first render ran the method twice (development mode checks each pass twice), and after three more passes it had run 8 times, while the pure pipe and the computed each ran once. After a signal change the computed ran again.
Key points
Template methods run on every check. Pure pipes run when the input reference changes. Computed runs when a dependency signal changes and caches.
Use `computed` for component state and a pure pipe for reusable formatting.
In-place mutation does not re-run a pure pipe.
Impure pipes run every check, so keep them cheap.
Common mistakes
Filtering or sorting a large list inside a template method.
Mutating an array and expecting a pure pipe to update.
Making a pipe impure to "fix" a mutation problem.
Follow-ups
Why does the `async` pipe have to be impure?
How would you memoize a method manually?
What changes under zoneless change detection?
Tips
Quote the run frequency of each option.
Give the rule of choice in two lines.
Mention measuring before refactoring.
Evaluation rubric
States how often each option runs.
Understands caching and dependency tracking.
Makes a reasoned choice.
168.angular-0168Mediummid
How does the track expression in @for affect performance and DOM reuse, and how can you measure the difference when a list is replaced with fresh data?
When the array is replaced with new objects, track $index or track item (object identity) reuses or recreates DOM based on position or reference. Tracking a stable id keeps the existing DOM elements for rows whose id remains, so only changed rows update. The difference shows as created or destroyed elements and lost input state.
Full answer
@for (row of rows(); track row.id) tells Angular how to match old items to new items when the array changes. Matching items keep their DOM nodes and component instances. Unmatched items are created or destroyed. This is both a performance and a correctness feature.
Consider a table loaded again from the server every few seconds. Each response gives new objects, with the same ids and mostly the same data.
track row (object identity): all objects are new, so no item matches. Angular destroys all old rows and creates all new ones. This is the slowest option, and the user loses focus, selection and text typed in a row's input.
track $index: the item at position 3 is matched with the new item at position 3. DOM nodes are reused and bindings update. This is fast for a fixed list. But if rows are inserted or removed at the top, every position shifts, so every row updates, and component state such as an input value stays with the position, not with the data row.
track row.id: matches by the stable key. If a row moved, Angular moves its DOM node. If a row is new, one node is created. Only rows with changed data update their bindings. This is the right default for lists of records.
Rules for a good key: unique inside the list, stable across reloads, and not changing when data changes. A duplicate key causes a development warning and wrong reuse. track $index is acceptable for static lists that never reorder, or for simple text rows.
How to measure: count created DOM nodes using a MutationObserver on the list (added and removed nodes), or keep a reference to a row element before the update and check it afterwards (sameNode). Add ngOnInit and ngOnDestroy counters in a row component. Use the Angular DevTools profiler or the browser Performance panel for time on large lists (1000 rows or more).
Beyond track: virtual scrolling for very long lists, pagination, and OnPush row components so unchanged rows are skipped.
typescript
import { Component, OnDestroy, OnInit, input, signal } from '@angular/core';
// Captured counts (Karma, Angular 20.3) with 5 rows:
// reload with new objects, same ids: track object -> 5 created, 5 destroyed
// track $index -> 0 created, 0 destroyed
// track id -> 0 created, 0 destroyed
// insert a row at the top: track object -> 6 created, 5 destroyed
// track $index -> 1 created, 0 destroyed, and the first DOM node now shows "Student 0"
// track id -> 1 created, 0 destroyed, and the first DOM node still shows "Student 1"
export const rowStats = { created: 0, destroyed: 0 };
@Component({ selector: 'app-row', template: `{{ label() }}` })
export class RowComponent implements OnInit, OnDestroy {
readonly label = input.required<string>();
ngOnInit(): void { rowStats.created++; }
ngOnDestroy(): void { rowStats.destroyed++; }
}
interface Student { id: number; name: string }
@Component({
selector: 'app-track-demo',
imports: [RowComponent],
template: `
@switch (mode()) {
@case ('object') { @for (s of students(); track s) { <app-row [label]="s.name" /> } }
@case ('index') { @for (s of students(); track $index) { <app-row [label]="s.name" /> } }
@case ('id') { @for (s of students(); track s.id) { <app-row [label]="s.name" /> } }
}
`,
})
export class TrackDemoComponent {
readonly mode = signal<'object' | 'index' | 'id'>('id');
readonly students = signal<Student[]>([]);
load(): void {
// A "server response": new objects with the same ids.
this.students.set([1, 2, 3, 4, 5].map((id) => ({ id, name: `Student ${id}` })));
}
reloadWithNewFirstRow(): void {
this.students.set([0, 1, 2, 3, 4, 5].map((id) => ({ id, name: `Student ${id}` })));
}
}
Angular 20.3, strict template check passes. A Karma test reloads the list with new objects and inserts a row at the top, for each tracking mode. The captured counts are in the comment.
Key points
`track` matches old and new items. Matches keep DOM and state.
With fresh objects, `track item` recreates everything. `track $index` reuses by position. `track id` reuses by identity of the record.
Keys must be unique and stable.
Measure with created and destroyed counters, or the profiler.
Common mistakes
Using `track row` (the object) when data is reloaded from the server.
Using `track $index` on a list where rows are inserted at the top.
Using a non-unique key such as the name.
Follow-ups
What happens in development mode if keys are duplicated?
How would you keep a selected row after a refresh?
When is `track $index` the right choice?
Tips
Describe the refresh scenario first.
Mention lost input state, not only speed.
Offer a way to measure.
Evaluation rubric
Explains matching by key for the three choices.
Gives rules for a good key.
Measures the effect with real counters.
169.angular-0169Mediummid
Predict the output: a computed, an effect and a signal updated several times in one function. When do computed and effect run, and how many times?
Signal writes are synchronous, but effects run later, during change detection, and see only the latest value. Computed values are lazy and cached, so they run when read after a change. Several writes before the effect runs give one effect run with the final value, and a computed read twice with no change runs once.
Full answer
This is a classic puzzle. The class has count = signal(0), double = computed(...) that logs "computed", and an effect that logs the value of double() and count(). A method then does count.set(1); count.set(2); count.set(3);.
Rules to apply:
Writing to a signal is immediate and synchronous. After count.set(1), count() returns 1 right away.
A computed is lazy. Changing count only marks the computed as stale. The function runs when somebody reads double(), and then the result is cached until the next change. Reading it twice with no change in between runs the function once.
An effect is scheduled. When a signal it read changes, Angular marks the effect dirty and runs it later, as part of change detection (for component effects, before the component's template is checked). It does not run in the middle of your method. So three writes in a row give one effect run, with count() === 3.
An effect always runs once on creation, after the first change detection pass, not inside the constructor.
If you set the same value that the signal already has (count.set(3) when it is 3), nothing is notified, because signals compare with Object.is.
In a component test, fixture.detectChanges() runs the component's pending effects. For root effects in services, use TestBed.tick().
So the output for the example is: the effect runs once at start with count 0, and after the three writes and one flush it runs once with count 3 (and double computed once for the new value). The intermediate values 1 and 2 are never seen by the effect.
Practical lessons: do not rely on an effect to see every value. If every value matters (for example, analytics for each click), use an event handler or an RxJS stream. Do not write to signals inside a computed. Avoid chains of effects that set signals for other effects. Use computed or linkedSignal for derived state.
Angular 20.3, strict template check passes. A Karma test captured the real log, shown in the comment: the effect ran once at start and once after the three writes, and the computed ran once per change.
Key points
Signal writes are synchronous. Effects run later and see the latest value only.
Computed values are lazy and cached.
Several writes before the flush give one effect run.
Setting an equal value does not notify.
Common mistakes
Expecting an effect to run for each of several writes.
Expecting a computed to run when its source changes, before anyone reads it.
Using effects to derive state.
Follow-ups
How do you make an effect see every value?
When exactly does a component effect run?
What does `untracked` do inside an effect?
Tips
Walk through the rules numerically, step by step.
State that effects are scheduled and computed are lazy.
Mention how you flush effects in tests.
Evaluation rubric
Predicts the output correctly.
Explains laziness, caching and scheduling.
Draws a practical lesson.
170.angular-0170Mediummid
When does an effect run, how do you stop it tracking a signal with untracked, and how do you clean up with onCleanup?
An effect runs after its first render and again when any signal read inside it changes. Wrap reads you do not want to track in untracked(). Use the onCleanup callback to cancel timers or listeners before the next run and when the effect is destroyed.
Full answer
An effect has two jobs: run code when signals change and keep the outside world (DOM, storage, logging, analytics) in sync. Dependencies are found automatically, only from signals that are actually read during a run.
Timing:
A component or directive effect runs during change detection, before the template of that component is checked. It runs once at first, and again after a tracked signal changed. Several changes before the next run give one run.
A root effect (created in a service with providedIn: 'root') runs as part of the application's change detection pass, too.
Effects need an injection context (constructor or field initialiser), or pass an injector. They stop when the owning component is destroyed.
untracked(() => ...) reads signals without making them dependencies. Example: log the userId whenever page changes, but do not re-run when userId changes. Inside untracked you can also call functions that read other signals, for example a service method, without accidentally subscribing to them.
onCleanup(fn) is the argument of the effect function. The fn runs before the next execution of the effect, and when the effect is destroyed. Use it for clearTimeout, removeEventListener or cancelling a request. Example: when query changes, start a timer for a debounced save, and clear the previous timer in the cleanup.
Writing signals in effects: since Angular 19, signal writes are allowed by default, but they create hidden chains, so keep them for rare cases. If the goal is derived state, use computed or linkedSignal. Use allowSignalWrites only on older versions.
Do not use effects for: copying one signal to another, calling HTTP on every change (use resource or toObservable with switchMap), and triggering navigation as the main data flow.
Test a component effect with fixture.detectChanges() (a root effect with TestBed.tick()), because it does not run at once. Use fake timers for the debounce.
typescript
import { Component, effect, signal, untracked } from '@angular/core';
export const events: string[] = [];
@Component({ selector: 'app-saver', template: `Page {{ page() }}` })
export class SaverComponent {
readonly page = signal(1);
readonly userId = signal('u1');
readonly draft = signal('');
constructor() {
// Tracks page only. Reading userId inside untracked does not add a dependency.
effect(() => {
const page = this.page();
const user = untracked(() => this.userId());
events.push(`visit page ${page} by ${user}`);
});
// Debounced save with cleanup: the old timer is cleared before each new run.
effect((onCleanup) => {
const text = this.draft();
if (!text) return;
const id = setTimeout(() => events.push(`saved "${text}"`), 20);
onCleanup(() => clearTimeout(id));
});
}
}
Angular 20.3, strict template check passes. A Karma test with fake timers (`fakeAsync`) checks that `userId` changes do not re-run the effect, that `page` changes do, and that the previous timer is cleared before the next one.
Key points
Effects run during change detection and batch several changes into one run.
Only signals read in a run become dependencies. `untracked` removes a read from tracking.
`onCleanup` runs before the next run and on destroy. Use it for timers and listeners.
Prefer `computed` and `linkedSignal` for derived state.
Common mistakes
Reading a signal in an effect and being surprised that it re-runs.
Forgetting cleanup, so timers pile up.
Using effects as a way to synchronise two signals.
Follow-ups
Why does an effect not run at the moment you set a signal?
How would you debounce an effect?
How do you create an effect outside the constructor?
Tips
Show `untracked` with a user id and a page.
Show `onCleanup` with a timer.
Mention how effects are flushed in tests.
Evaluation rubric
Explains effect timing and dependency tracking.
Uses `untracked` and `onCleanup` correctly.
Knows what effects are not for.
171.angular-0171Mediummid
How do you bind properties and listen to events on a component's host element, and how does the host metadata compare with @HostBinding and @HostListener?
The host element is the tag of the component itself. The host metadata object sets attributes, classes, styles and listeners on it, for example '[class.active]': 'active()' and '(click)': 'toggle()'. @HostBinding and @HostListener do the same with decorators. The host object is the recommended form in new code, and works well with signals.
Full answer
Every component or directive is attached to a host element, such as <app-toggle> in the parent's template. Sometimes the component itself must change its host: add a CSS class, set role and tabindex, or react to a click on the whole component. The parent should not need to do this.
A plain key such as role: 'switch' sets a static attribute.
'[class.on]': 'on()' binds a class to an expression. [style.width.px], [attr.x] and [prop] bindings work in the same way.
'(click)': 'toggle()' listens to an event, with $event available. Key filters such as keydown.enter work.
Global targets: '(window:resize)': 'onResize($event)' or '(document:keydown.escape)': 'close()'.
Decorator form: @HostBinding('class.on') get isOn() { return this.on(); } and @HostListener('click') toggle() {...}. It works and is common in older code, but it splits host behaviour across the class, and it cannot read signals as neatly. The Angular style guide prefers the host object, and a lint rule can enforce it.
Rules and tips:
Host bindings are checked during change detection of the parent view. Keep them cheap.
Do not read the DOM in a host binding.
A listener on the host with a global target (window:) is removed when the component is destroyed. You do not need to unsubscribe.
For accessibility, a clickable host needs a role, tabindex and keyboard handling, as in the example. Prefer a native button inside when you can.
Directives can use host too, which is how tooltips, focus rings and click-outside directives work.
Compared with ElementRef and Renderer2, host metadata is declarative, and works with server rendering because Angular applies it through the renderer.
typescript
import { Component, HostBinding, HostListener, signal } from '@angular/core';
@Component({
selector: 'app-switch',
template: `<ng-content />`,
host: {
role: 'switch',
tabindex: '0',
'[class.on]': 'on()',
'[attr.aria-checked]': 'on()',
'(click)': 'toggle()',
'(keydown.enter)': 'toggle()',
},
})
export class SwitchComponent {
readonly on = signal(false);
toggle(): void {
this.on.update((v) => !v);
}
}
// The same idea with the older decorators:
@Component({ selector: 'app-switch-old', template: `<ng-content />` })
export class OldSwitchComponent {
isOn = false;
@HostBinding('class.on') get on(): boolean {
return this.isOn;
}
@HostListener('click') toggle(): void {
this.isOn = !this.isOn;
}
}
Angular 20.3, strict template check passes. A Karma test clicks the host, presses Enter, and checks the class and the ARIA attribute. The decorator form is shown with a comment and was type-checked in the same file.
Key points
The host element is the component's own tag. Use `host` metadata for attributes, classes, styles and listeners on it.
`@HostBinding` and `@HostListener` are the older decorator forms.
Add `role`, `tabindex` and keyboard handling for clickable hosts.
Global listeners such as `window:resize` are cleaned up automatically.
Common mistakes
Making the host clickable without keyboard support.
Reading the DOM inside a host binding expression.
Adding manual `addEventListener` code when `host` would do.
Follow-ups
How do you listen to `window:resize` from a directive?
Why does the style guide prefer `host` metadata?
How do you set a CSS variable on the host?
Tips
Show one binding and one listener in the host object.
Mention accessibility for clickable hosts.
Say that the decorators still work.
Evaluation rubric
Explains host element and the metadata forms.
Uses bindings, listeners and key filters correctly.
Adds accessibility and lifecycle notes.
172.angular-0172Mediummid
What does "NG0203: inject() must be called from an injection context" mean, and how do you fix it?
inject() works only while Angular is creating something (constructor, field initialiser, factory, a provider function, or inside runInInjectionContext). Calling it later, such as in a click handler, a setTimeout or a subscribe callback, throws NG0203. Fix by calling inject() early and keeping the result, or by keeping the Injector and using runInInjectionContext.
Full answer
inject() asks the current injector for a dependency. For that to work, Angular must be in the middle of creating a class or running a function that is tied to an injector. This is the injection context. It is available:
in a constructor and in field initialisers of a component, directive, pipe or service,
in a provider factory (useFactory, InjectionToken factory) and in provideAppInitializer,
in functional guards, resolvers, interceptors and canMatch functions (the router calls them in an injection context),
inside runInInjectionContext(injector, fn), and in TestBed.runInInjectionContext.
It is not available in lifecycle hooks such as ngOnInit, in event handlers, in setTimeout or subscribe callbacks, and after an await. In those places, inject() throws:
In Angular 20 the message reads: NG0203: The Clocktoken injection failed.inject()function must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used withrunInInjectionContext. Older versions start with inject() must be called from an injection context.
The same message appears for takeUntilDestroyed() without an argument, effect(), toSignal() and viewChild() when they are called late, because they use inject() inside.
Fixes:
Move the call to a field initialiser: private readonly router = inject(Router);. Use the field later. This fixes most cases.
For a helper that needs the injector later, keep it: private readonly injector = inject(Injector); and run runInInjectionContext(this.injector, () => inject(Service)). Use this sparingly.
For takeUntilDestroyed, effect and toSignal, pass destroyRef or { injector } as an option, or create them in the constructor.
In a helper function that uses inject, call that helper only from an injection context, and name it clearly (for example injectUser()).
Why this design: it keeps dependency injection implicit and short, without passing injectors around. The price is the rule that you must call inject while Angular is building the object.
Quick check when you see NG0203: look at the stack. Find the first of your own functions, and ask "who calls this, and when?".
typescript
import { Injectable, Injector, inject, runInInjectionContext } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class Clock {
now(): string {
return 'now';
}
}
@Injectable({ providedIn: 'root' })
export class Reports {
private readonly clock = inject(Clock); // fix 1: inject while Angular builds the object
private readonly injector = inject(Injector); // fix 2: keep the injector for later
broken(): string {
return inject(Clock).now(); // NG0203 when called later
}
fixedWithField(): string {
return this.clock.now();
}
fixedWithContext(): string {
return runInInjectionContext(this.injector, () => inject(Clock).now());
}
}
Angular 20.3, type-checked. A Karma test calls the broken method and checks that the message starts with NG0203 and names the `Clock` token, then runs the fixed versions.
Key points
`inject()` works only in an injection context: constructors, field initialisers, factories, router functions and `runInInjectionContext`.
Calling it in `ngOnInit`, event handlers, timers or after `await` throws NG0203.
Fix by injecting into fields, or by keeping an `Injector` and using `runInInjectionContext`.
`effect`, `toSignal` and `takeUntilDestroyed` also need a context or an explicit injector or `destroyRef`.
Common mistakes
Calling `inject()` inside `ngOnInit` or a click handler.
Using `takeUntilDestroyed()` without an argument outside the constructor.
Creating a global helper that calls `inject()` from random places.
Follow-ups
How do functional guards get an injection context?
How would you call a helper that uses `inject` from a callback?
Why does `inject` after an `await` fail?
Tips
List where the context exists before the fix.
Mention that other APIs rely on it too.
Give the field initialiser fix first.
Evaluation rubric
Explains the injection context and where it exists.
Recognises the error and its common causes.
Gives correct fixes.
173.angular-0173Mediummid
What causes "NG0100: ExpressionChangedAfterItHasBeenCheckedError", why does it appear only in development, and what are the right fixes?
In development mode Angular runs a second check after every pass. If a binding value changed between the two checks, it throws NG0100, because a child or hook changed state after the parent already rendered it. Fix the data flow: compute the value earlier, use signals, or move the update to a later turn such as afterNextRender.
Full answer
Change detection goes from the parent down to the children. After a parent has rendered its bindings, a later step (a child's ngAfterViewInit, a child's setter, a method with side effects) changes something that the parent already displayed. The screen would then show an old value, and the next check would change it again. Angular treats this as a bug in the data flow.
To find such bugs, development mode runs checkNoChanges after each pass: it evaluates all bindings again and compares them with the values in the first pass. If one differs, it throws NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'x'. Current value: 'y'. Production builds skip the second pass, so the error does not appear there, but the screen may show a stale value. So it is a real bug, not only a development warning.
Typical causes:
A child changes a parent's field in ngAfterViewInit or ngAfterContentInit.
A getter or method that returns a different value on each call (Math.random(), new Date(), a counter that increments).
A service that is updated while a template that reads it is being rendered (for example, a loading flag set in a child's constructor).
Content projection or @ViewChild values used in the parent's template before they exist.
Fixes, from best to worst:
Restructure so data flows down: compute the value in the parent (or in a computed) before it is rendered, and pass it down as an input.
Use signals. A signal written in a hook marks the view dirty again, and Angular re-renders, so the second check passes. In many cases, replacing a plain field by a signal is the whole fix.
Move the update after rendering with afterNextRender, or schedule it with queueMicrotask or setTimeout. This is a work-around and delays the update by one turn.
Call cdr.detectChanges() after the change. It works but hides the design problem.
Do not "fix" it by ignoring the error or by disabling the check.
typescript
import { AfterViewInit, Component, Output, EventEmitter, signal } from '@angular/core';
@Component({ selector: 'app-child', template: `child` })
export class ChildComponent implements AfterViewInit {
@Output() ready = new EventEmitter<string>();
ngAfterViewInit(): void {
this.ready.emit('child ready'); // runs after the parent has already rendered its bindings
}
}
@Component({
selector: 'app-broken-parent',
imports: [ChildComponent],
template: `<p>Status: {{ status }}</p><app-child (ready)="status = $event" />`,
})
export class BrokenParentComponent {
status = 'waiting'; // plain field: NG0100 in development
}
@Component({
selector: 'app-fixed-parent',
imports: [ChildComponent],
template: `<p>Status: {{ status() }}</p><app-child (ready)="status.set($event)" />`,
})
export class FixedParentComponent {
readonly status = signal('waiting'); // signal: the view is refreshed again
}
Angular 20.3, strict template check passes. A Karma test renders the broken parent and checks that NG0100 is thrown, then renders the signal-based fix and checks that there is no error and the text is updated.
Key points
NG0100 means a binding value changed between the first check and the development-only second check.
It happens when a child or hook changes state that a parent already rendered.
Production skips the check, but the stale screen bug can still exist.
Fix by moving data flow down, using signals, or updating after render.
Common mistakes
Treating the error as a development-only nuisance.
Using `setTimeout` everywhere without understanding the cause.
Returning random or time based values from template methods.
Follow-ups
Why does a signal fix the error in many cases?
Why does it not appear in a production build?
How does `detectChanges()` hide the problem?
Tips
Explain the second pass first.
Give the `ngAfterViewInit` child to parent case.
Order the fixes by quality.
Evaluation rubric
Explains the check and the cause.
Lists realistic causes.
Gives sound fixes in a good order.
174.angular-0174Mediummid
How do you read Angular error codes, and what do NG0300 (multiple components match) and NG0950 (required input has no value yet) mean?
Angular errors carry a code such as NG0300, and angular.dev/errors has a page for each with causes and fixes. NG0300 means two components match the same element, usually because of a duplicate selector. NG0950 means a required input was read before the parent set it, for example in the constructor or a field initialiser.
Full answer
Since Angular 14, errors have a stable code and a link: NG0300, with https://angular.dev/errors/NG0300. The page explains the cause and fixes. Search the code, not the long message, because messages change between versions. Ranges help: NG0xxx are run time errors, and NG8xxx are template compiler errors (for example NG8001 unknown element).
NG0300: Multiple components match node with tagname 'app-dup'. An element in a template matched the selectors of two or more components (only one component can own an element). Causes:
Two components with the same selector, both imported in the same parent (a copy and paste mistake, or a library that uses the same selector as yours).
A very general selector such as div or [title] on a component, which matches elements by accident.
Fixes: give each component a unique prefix (app-, school-), check the imports of the component, and make selectors specific. Use the editor's "go to definition" on the tag to see which one matched.
NG0950: Input is required but no value is available yet. A required signal input (input.required<T>()) was read before Angular set it. Inputs are set after the constructor runs, so reading this.id() in the constructor, in a field initialiser, or in a computed that is read too early fails. The compiler reports a direct read in a constructor as NG8118. Fixes: read the input in ngOnInit, in a computed that is read from the template, or in an effect. If a default is acceptable, make the input optional with input(0).
Related codes worth knowing: NG0100 (changed after checked), NG0200 (circular dependency), NG0201 (no provider), NG0203 (outside injection context), NG0912 (component ID collision, a warning), NG0913 (image much larger than it is shown), NG0500 to NG0505 (hydration problems).
Debug routine: copy the code, open the docs page, read the stack to find the first line of your own code, and reproduce in the smallest example. Keep the Angular version in mind, because new versions add and rename codes.
typescript
import { Component, input } from '@angular/core';
@Component({ selector: 'app-dup', template: `a` })
export class AComponent {}
@Component({ selector: 'app-dup', template: `b` })
export class BComponent {}
@Component({
selector: 'app-dup-host',
imports: [AComponent, BComponent], // both match <app-dup />: NG0300
template: `<app-dup />`,
})
export class DupHostComponent {}
@Component({ selector: 'app-id-view', template: `Id: {{ id() }}` })
export class IdViewComponent {
readonly id = input.required<number>();
readSoon(): number {
return this.id(); // NG0950 when called before the parent sets the input
}
}
Angular 20.3. A Karma test reproduces NG0300 with two components that share a selector, and NG0950 by reading a required input before it is set. The exact message starts are checked. Both bad components compile without a compiler error in AOT here, so the errors appear at run time.
Key points
Error codes (NG0xxx runtime, NG8xxx template compiler) link to pages with causes and fixes.
NG0300: more than one component matches an element, often a duplicate or too general selector.
NG0950: a required input was read before it was set. Read it in `ngOnInit`, a template-read `computed` or an `effect`.
Search by code, and read your own first stack line.
Common mistakes
Searching the whole message text instead of the code.
Reusing a selector in two components that are imported together.
Reading a required input in the constructor.
Follow-ups
What kind of errors are the NG8xxx codes?
How would you avoid selector clashes in a shared library?
How can an `effect` read a required input safely?
Tips
Show that you use the docs page for each code.
Explain the cause of both codes in one sentence each.
Offer a repeatable debugging routine.
Evaluation rubric
Understands error code families and docs.
Explains NG0300 and NG0950 causes and fixes.
Describes a debugging method.
175.angular-0175Mediummid
Compare take, first, takeWhile, takeUntil and last in RxJS. Which one do you use to stop a stream, and what happens on an empty stream?
take(n) completes after n values. first() completes after the first value (or the first that matches) and errors if the source completes empty. takeWhile completes when a condition turns false. takeUntil completes when another observable emits. last emits the final value when the source completes, so it needs a source that ends.
Full answer
All of these operators complete the stream early, but they decide when in different ways.
take(n): emits the first n values and then completes and unsubscribes from the source. If the source completes with fewer values, you get only those. No error.
first() and first(predicate): emits the first value (or the first that passes the predicate) and completes. If the source completes without a matching value, it throws EmptyError (no elements in sequence), unless you give a default: first(undefined, defaultValue). Use take(1) when an empty result is acceptable.
takeWhile(predicate, inclusive?): emits while the predicate is true, and completes at the first false value. That value is dropped unless inclusive is true. Good for "until the progress reaches 100".
takeUntil(notifier$): emits until the notifier emits, and then completes. This is the classic way to stop a stream when a component is destroyed (takeUntil(this.destroy$)), now mostly replaced by takeUntilDestroyed(). The notifier must come last in the pipe, or an inner subscription created after it can leak.
last(): waits until the source completes and then emits the final value. On an endless source it never emits. On an empty source it throws EmptyError too.
skip, skipWhile and skipUntil are the matching operators that ignore values at the start.
Common uses:
HTTP: http.get already completes, so you do not need take(1).
store.select(...).pipe(first()) or take(1) to read the current value once.
A countdown with interval(1000).pipe(take(5)).
A polling loop with takeWhile(status => status !== 'done', true) (inclusive, so the final status is also emitted).
Completion matters because complete runs the teardown logic and lets forkJoin, concat and toArray finish. A stream that never completes can hold memory and subscriptions.
RxJS 7.8. The script was run in Node 24 twice with identical output. It prints the results for a normal stream and for an empty stream.
Key points
`take(n)` is silent on short sources. `first()` errors on an empty source. `last()` needs completion.
`takeWhile` stops at the first false value (use `inclusive` to emit it). `takeUntil` stops on a notifier.
Put `takeUntil` last in the pipe. Prefer `takeUntilDestroyed()` in components.
Early completion runs teardown and lets other operators finish.
Common mistakes
Using `first()` when the source may be empty.
Putting `takeUntil` before `switchMap`, which can leak the inner subscription.
Expecting `last()` to work on an endless stream.
Follow-ups
What does `takeWhile(fn, true)` change?
How is `take(1)` different from `first()`?
Why is the position of `takeUntil` important?
Tips
Give the empty stream behaviour of each operator.
Mention `takeUntilDestroyed` as the modern choice.
Use a polling example for `takeWhile`.
Evaluation rubric
Describes each operator's stopping rule.
Knows the empty stream and error cases.
Applies them to realistic cases.
176.angular-0176Mediummid
What are the options for unit testing an Angular app (Karma, Jest, Vitest), and what is the direction the Angular team has taken?
Karma with Jasmine ran tests in a real browser and was the long-time default, but the Karma project is deprecated. Jest is popular through community presets, and runs in Node with jsdom. Vitest is the direction the Angular team chose: ng test uses Vitest by default for new projects in Angular 21, and Karma stays supported. Experimental Jest and Web Test Runner support is deprecated.
Full answer
Unit tests need a runner (finds and runs tests, reports results), an assertion library, and an environment (a browser or a simulated DOM).
Karma and Jasmine: the classic Angular setup. Karma launches real Chrome, and Jasmine provides describe, it, expect and spies. Benefits: real browser behaviour (layout, real events). Drawbacks: slower start, heavier setup, and the Karma project was deprecated in 2023, so the Angular team looked for a replacement.
Jest: a very popular runner from the React world, with fast start, snapshots, and good mocking. It runs in Node with jsdom, so there is no real browser. In Angular it is used through community packages (jest-preset-angular, the Nx Jest plugin). The CLI also had an experimental Jest builder, which is deprecated.
Vitest: a modern runner built on Vite, with a Jest-like API, watch mode, and an option to run in a real browser (Playwright or WebdriverIO providers). The Angular team announced that ng test runs Vitest by default for new projects in Angular 21, and that Vitest support is stable. New projects include vitest and jsdom. Existing Karma projects keep working, and there is an experimental schematic (refactor-jasmine-vitest) that converts Jasmine style tests.
Key differences in daily work:
Environment: jsdom (Node, fast, not a real browser) versus a real browser (Karma, or Vitest browser mode).
API: jasmine.createSpy and spyOn versus vi.fn() and vi.spyOn. Timers: fakeAsync works with zone.js, and vi.useFakeTimers() works with Vitest, so tests for zoneless apps are different.
Speed: Node based runners start faster.
Migration cost: mostly mock syntax, timers and configuration.
How to answer in an interview: say what your project uses and why, name the direction (Vitest, Karma still supported), mention that real browser tests (Playwright component tests, Vitest browser mode, or e2e) cover what jsdom cannot, and show that you would migrate gradually. Keep tests written against behaviour (rendered output, harnesses), because those survive a runner change.
typescript
// Same behaviour test: only the spy and the test API differ between the two runners.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `<button (click)="inc()">Count {{ count() }}</button>`,
})
export class CounterComponent {
readonly count = signal(0);
inc(): void {
this.count.update((c) => c + 1);
}
}
// Karma and Jasmine:
// const log = jasmine.createSpy('log');
// expect(log).toHaveBeenCalledWith('ok');
//
// Vitest:
// const log = vi.fn();
// expect(log).toHaveBeenCalledWith('ok');
//
// The component test body is the same in both:
// const fixture = TestBed.createComponent(CounterComponent);
// fixture.nativeElement.querySelector('button').click();
// fixture.detectChanges();
// expect(fixture.nativeElement.textContent).toContain('Count 1');
This is based on the Angular 21 announcement and the Angular testing guides (checked on angular.dev in December 2026). The code was only type-checked. The Vitest form was not run here, because the test project uses Karma.
Key points
Karma (real browser) is the long-time default, but the Karma project is deprecated.
Jest runs in Node with jsdom and is used through community presets. The CLI's experimental Jest support is deprecated.
Vitest is the Angular team's default for new projects in Angular 21. Karma remains supported.
Behaviour based tests and harnesses survive a runner change. Use real browser tests where jsdom is not enough.
Common mistakes
Saying Karma is removed. It is still supported.
Assuming jsdom behaves like a real browser for layout.
Migrating all tests at once without a plan.
Follow-ups
What does a migration from Jasmine spies to Vitest involve?
Which tests need a real browser?
How do fake timers differ without zone.js?
Tips
Be exact: Vitest is the default for new projects, and existing Karma projects still work.
Mention the jsdom limit.
Suggest gradual migration.
Evaluation rubric
Compares the three options accurately.
States the Angular team direction correctly.
Talks about migration and test design.
177.angular-0177Mediummid
How do Cypress and Playwright compare for end-to-end testing of an Angular app, and what makes an e2e test reliable?
Both run real browser tests and wait automatically for elements. Playwright drives Chromium, Firefox and WebKit from outside the page, runs tests in parallel, supports several tabs and users, and has a trace viewer. Cypress runs inside the browser with a strong interactive runner. Protractor was removed, so new projects pick one of these. Reliable tests use stable selectors, no fixed sleeps and controlled data.
Full answer
End-to-end (e2e) tests open the real app in a real browser and act like a user: type, click, check the screen. They cover the full path including routing, the template, the API and the backend (or a mocked backend).
Protractor, the old Angular e2e tool, was deprecated and removed (Angular 15 dropped it from the CLI), so teams choose Cypress or Playwright. ng e2e has no built-in default runner: you add one with a schematic or by installing the package.
Playwright:
Controls browsers from outside through a protocol. Chromium, Firefox and WebKit are supported, so you can test Safari-like behaviour.
Tests run in parallel by default, in isolated browser contexts (fast, clean state).
Several tabs, several users and file downloads are easy. Auto-waiting for actionability and web-first assertions (expect(locator).toHaveText(...) retries).
Trace viewer, screenshots, video, codegen to record tests.
Written in TypeScript, with its own test runner.
Cypress:
Runs the test code inside the browser next to the app, so it has direct access to the page and network stubbing (cy.intercept).
A very good interactive runner with time travel snapshots, which many people find friendly for beginners.
Commands are queued and retried automatically. It is single-tab by design, and cross-origin flows need cy.origin.
Component testing mode exists for Angular components.
Choose by needs: cross-browser and parallel speed favours Playwright. Developer experience in a single app and a big plugin world favours Cypress. Many teams now start with Playwright.
Making e2e reliable:
Select by role or test id (getByRole('button', { name: 'Save' })), not by CSS classes or position.
Never use fixed sleeps. Rely on auto-waiting and assertions that retry.
Control data: seed the backend, or mock the network for unrelated services.
Keep tests independent, and log in through an API or stored state, not through the screen each time.
Test a few critical journeys, because e2e is slow. Leave details to unit and component tests.
Run in CI with retries only as a safety net, and record traces for failures.
typescript
import { expect, test } from '@playwright/test';
test('student can log in and see the report card', async ({ page }) => {
await page.goto('http://localhost:4200/login');
await page.getByLabel('Email').fill('asha@example.com');
await page.getByLabel('Password').fill('correct-horse');
await page.getByRole('button', { name: 'Log in' }).click();
// Web-first assertions retry until the text appears. No fixed sleeps.
await expect(page.getByRole('heading', { name: 'Report card' })).toBeVisible();
await expect(page.getByTestId('total-marks')).toHaveText('412');
});
`@playwright/test` is installed for type checking only. The spec compiles, but it was not run, because no browser download or running app was available here.
Key points
Protractor is gone. Playwright and Cypress are the usual choices, with no default in `ng e2e`.
Use role or test id selectors, auto-waiting, controlled data and no fixed sleeps.
Keep e2e for critical journeys.
Common mistakes
Using `sleep(2000)` instead of waiting for a condition.
Selecting by CSS class names that change.
Logging in through the UI in every test.
Follow-ups
How do you test a flow that opens a second tab?
How would you speed up an e2e suite in CI?
What belongs in e2e and what in unit tests?
Tips
Pick a side and give a reason, but show you know the other.
Say what you do against flaky tests.
Mention the test pyramid.
Evaluation rubric
Compares both tools accurately.
Knows the status of Protractor and `ng e2e`.
Lists reliability practices.
178.angular-0178Mediummid
What is Angular Elements, how do you package a component as a custom element, and what are its limits?
Angular Elements converts an Angular component into a standard custom element (Web Component) with createCustomElement and customElements.define. Inputs become properties and attributes, outputs become DOM events, and the tag works in any page or framework. The cost is that each element bundles Angular unless the apps share one runtime, and projection and styling have limits.
Full answer
A custom element (Web Component) is a browser standard: you define a tag such as <school-rating>, and the browser creates it anywhere in HTML. Angular Elements (@angular/elements) wraps an Angular component so it works as one.
How to do it:
Install @angular/elements.
Create the element class: const Rating = createCustomElement(RatingComponent, { injector }). The injector comes from the running application (for example createApplication() or app.injector).
Use it in any HTML: <school-rating value="4"></school-rating>.
Mapping rules:
Each component input becomes a property of the element, and an attribute in dash case (maxStars becomes max-stars). Attributes are always strings, so use an input transform (numberAttribute) when needed.
Each output becomes a DOM CustomEvent. The emitted value is in event.detail.
Change detection runs for the element, and when the element is removed from the page it is destroyed, with cleanup.
Where it is useful: adding an Angular widget to a CMS or non-Angular page, sharing one component between apps built with different frameworks, and a step in migrations or micro-frontend setups where teams use different versions.
Limits and costs:
Bundle size. Each Angular Elements bundle includes Angular's runtime. Several separate bundles on one page load the framework several times, unless you share one application and register many elements.
Content projection is limited. ng-content works at creation time, but dynamic projected content does not behave like in a normal Angular template.
Styling: with ViewEncapsulation.ShadowDom styles are isolated, with Emulated they use attributes. Global CSS may or may not reach the content.
No router, SSR support is limited, and zone.js or zoneless mode must be chosen once for the page.
Older browsers need polyfills. All current browsers support custom elements.
Name elements with a dash and a prefix, as the standard requires, and document the properties and events as the public API.
typescript
import { Component, EnvironmentInjector, Injector, input, numberAttribute, output } from '@angular/core';
import { createCustomElement } from '@angular/elements';
@Component({
selector: 'app-rating',
template: `
<span>Stars: {{ value() }}</span>
<button type="button" (click)="rated.emit(value() + 1)">Rate higher</button>
`,
})
export class RatingComponent {
readonly value = input(0, { transform: numberAttribute });
readonly rated = output<number>();
}
export function defineRatingElement(injector: Injector | EnvironmentInjector, tag: string): void {
const element = createCustomElement(RatingComponent, { injector: injector as Injector });
customElements.define(tag, element);
}
// In any HTML page after defineRatingElement(injector, 'school-rating'):
// <school-rating value="4"></school-rating>
// el.addEventListener('rated', (e) => console.log(e.detail));
Angular 20.3 with `@angular/elements` 20.3. A Karma test defines the element, sets an attribute and a property, clicks the button, and reads the `CustomEvent` detail. Defining the same tag a second time threw a `NotSupportedError`.
Key points
`createCustomElement(Component, { injector })` plus `customElements.define('tag-name', Element)`.
Inputs become properties and attributes (strings). Outputs become `CustomEvent`s with data in `detail`.
Good for embedding Angular widgets in other pages and for mixed framework setups.
Costs: bundle size, projection and styling limits, no router, one runtime per page.
Common mistakes
Forgetting that attribute values are strings.
Loading a full Angular bundle several times on one page.
Defining the same tag name twice (the browser throws an error).
Follow-ups
How do you read an output value in plain JavaScript?
How would you share Angular between several elements?
When would you choose Module Federation instead?
Tips
Show the four steps in order.
Explain the mapping of inputs and outputs.
Be honest about the costs.
Evaluation rubric
Describes the packaging steps correctly.
Explains input and output mapping.
Names real limits and use cases.
179.angular-0179Mediummid
What was Angular Universal, how did server-side rendering change in Angular 17 to 20, and what does the modern setup look like?
Angular Universal was the separate project (@nguniversal) for server-side rendering. In Angular 17 it moved into the CLI as @angular/ssr, with the application builder, built-in prerendering and non-destructive hydration. Later versions added event replay, incremental hydration, and route-level render modes (server, client, prerender), so one app can mix SSR, SSG and CSR.
Full answer
Server-side rendering (SSR) means the server sends finished HTML for the first view, so users and search engines see content before the JavaScript loads. In the Angular world this was called Angular Universal.
History in short:
Early versions: Universal was a separate project and a separate set of packages (@nguniversal/express-engine and others). You wrote a server.ts file, an extra AppServerModule, and extra build targets.
Hydration: before Angular 16, the browser threw the server HTML away and rendered again, which caused a flash and wasted work. Angular 16 introduced hydration as a preview, and Angular 17 made it stable. provideClientHydration() reuses the server DOM.
Angular 17: Universal was folded into the CLI. ng new --ssr and ng add @angular/ssr set it up. The new application builder (esbuild and Vite) builds browser and server code, and supports prerendering (static site generation) at build time.
Angular 18 and 19: event replay (clicks made before hydration finished are replayed), incremental hydration with @defer (hydrate on viewport), route-level render modes in the server routes file (RenderMode.Server, Client or Prerender) and a new request handling API (AngularNodeAppEngine, AngularAppEngine) that also runs on edge platforms. Several of these were preview features and became stable by Angular 20.
What the modern setup has:
@angular/ssr and @angular/platform-server.
app.config.server.ts that merges the app config with provideServerRendering().
app.routes.server.ts with a render mode for each route: Prerender for pages that rarely change, Server for personal pages, Client for dashboards behind login.
provideClientHydration(withEventReplay()) in the browser config.
TransferState (automatic for HttpClient GET requests) so data is not fetched twice.
Rules of thumb: use prerendering when content is the same for everybody, SSR when content changes per request, and plain client rendering when SEO and first paint do not matter. Keep browser-only code in afterNextRender, and avoid direct window access.
Interview tip: say "Universal is now part of Angular itself (@angular/ssr)", and name hydration as the key change.
Angular 20.3 with `@angular/ssr` 20.3, type-checked. The server routes file shows the real API shape. The server was not started here, so no page was rendered.
Key points
Universal was a separate SSR project. Since Angular 17 it is part of the CLI as `@angular/ssr`.
Hydration reuses server HTML. Event replay and incremental hydration reduce lost clicks and work.
Route-level render modes mix server, client and prerendered pages in one app.
Browser-only code belongs in `afterNextRender`.
Common mistakes
Referring to `@nguniversal` packages for new projects.
Using SSR for pages that never change, where prerendering is cheaper.
Reading `window` or `localStorage` during server rendering.
Follow-ups
When would you prerender and when use SSR?
What does event replay solve?
How does `TransferState` avoid duplicate HTTP calls?
Tips
Tell the story in four steps: Universal, hydration, CLI integration, render modes.
Match render mode to page type.
Mention the browser-only rule.
Evaluation rubric
Gives a correct short history.
Describes the modern setup and its parts.
Chooses render modes sensibly.
180.angular-0180Mediummid
How do you migrate an existing NgModule application to standalone components with the Angular schematic, and what do you check after each step?
Run ng generate @angular/core:standalone three times, choosing a different mode each time: convert declarations to standalone, remove unnecessary NgModules, then bootstrap with standalone APIs. Build and test after each step and commit it separately. Other schematics convert control flow, inject(), signal inputs and outputs.
Full answer
Migrating to standalone is a step by step process with a schematic, not a rewrite. Prepare first: update to a recent Angular version with ng update, make sure the build and tests pass, and commit.
Run ng generate @angular/core:standalone and choose the mode. The recommended order:
Convert all components, directives and pipes to standalone. The schematic sets standalone: true where needed (or removes the flag in newer versions where it is the default), moves their template dependencies into imports, and updates the modules that declared them. Build, run tests, and commit.
Remove unnecessary NgModule classes. Modules that now only re-export or import other things can be deleted. The schematic keeps modules that have providers or routing configuration it cannot safely remove. Build, test, commit.
Bootstrap the project using standalone APIs. It replaces platformBrowserDynamic().bootstrapModule(AppModule) with bootstrapApplication(AppComponent, appConfig), and moves providers (HttpClientModule becomes provideHttpClient(), RouterModule.forRoot becomes provideRouter). Build, test, run the app, commit.
After the schematic, finish by hand: remove unused modules, check lazy routes (loadChildren to a module still works, and can be changed to loadComponent or a routes array), review the imports arrays for unused entries, and fix tests that used declarations. Large apps can migrate a folder at a time using the path option.
Common problems: modules with forRoot() providers need manual conversion to provider functions, a third party library that is still module-based is imported by its module (this is fine), entryComponents leftovers, and schematics skipping files with unusual patterns (check the log).
Other helpful migrations in the same style: @angular/core:control-flow (templates to @if, @for, @switch), @angular/core:inject (constructor injection to inject()), @angular/core:signal-input-migration, output-migration, and signal-queries-migration. Run them one at a time, with a clean commit between runs, so review stays easy.
Standalone is optional to adopt, and NgModules still work, but new Angular features and documentation assume standalone.
typescript
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter, Routes } from '@angular/router';
// Before (module based main.ts):
// platformBrowserDynamic().bootstrapModule(AppModule);
// AppModule imports: BrowserModule, HttpClientModule, RouterModule.forRoot(routes)
//
// After step 3 (standalone):
const routes: Routes = [];
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes), // was RouterModule.forRoot(routes)
provideHttpClient(), // was HttpClientModule
],
};
// main.ts: bootstrapApplication(AppComponent, appConfig).catch(console.error);
This describes the Angular CLI schematics for Angular 20. The schematics were not run here. The sample shows the result shape of step 3 (a standalone bootstrap), and it was type-checked.
Key points
Run `ng generate @angular/core:standalone` three times: convert, prune modules, switch bootstrap.
Build, test and commit after each step.
Finish by hand: `forRoot` providers, lazy routes, unused imports and test setup.
Other schematics migrate control flow, `inject()`, signal inputs, outputs and queries.
Common mistakes
Running all steps in one commit, so problems are hard to trace.
Expecting the schematic to rewrite `forRoot()` providers.
Migrating without updating Angular first.
Follow-ups
How do you migrate only one feature folder?
What happens to lazy loaded modules?
Which other schematics would you run next?
Tips
Give the three modes in order and one check per step.