Practice exam
For each question, think first or write your answer. Then open the answer and mark yourself honestly. The result stays only in your browser.
/ 16
1. A flash sale banner with a timer
Question: Our online shop shows a flash sale banner on the product page. It counts down every second and also shows the number of items in the cart. Users open many product pages in one visit, often 30 or more. Here is the component:
import { Component, OnInit, inject, signal } from '@angular/core';
import { interval } from 'rxjs';
import { CartStore } from './cart.store';
@Component({
selector: 'app-sale-banner',
template: `<p>Sale ends in {{ secondsLeft() }} s. Cart: {{ cartCount() }}</p>`,
})
export class SaleBanner implements OnInit {
private readonly cartStore = inject(CartStore);
readonly secondsLeft = signal(600);
readonly cartCount = signal(0);
ngOnInit() {
interval(1000).subscribe(() => this.secondsLeft.update(s => Math.max(0, s - 1)));
this.cartStore.count$.subscribe(n => this.cartCount.set(n));
}
}
The CartStore is a root service, and count$ comes from a BehaviorSubject. You see this in code review. What do you think? Is there a problem?
Short answer: Neither subscription is ever closed. When the user leaves the product page, the component is destroyed, but the timer and the cart subscription keep running and keep the component in memory. Each product page visit adds one more timer and one more cart subscription. The fix is to tie the subscriptions to the component’s life: toSignal, the async pipe, or takeUntilDestroyed.
Hint (if the candidate says there is no problem): After visiting 30 product pages, the browser memory tool shows 30 SaleBanner objects that are never freed. A breakpoint in the timer callback is hit 30 times each second.
Why does this happen? (step by step)
- The interval function makes an observable that never completes. It emits forever until someone unsubscribes.
- The subscribe method returns a Subscription. The code throws it away, so nobody can ever call unsubscribe.
- The callback uses this, so the timer holds a reference to the component. The garbage collector cannot free the component.
- The CartStore lives as long as the app. Its BehaviorSubject keeps a list of its subscribers, so it also holds each old component.
- Angular destroys the component’s view, but it does not know about subscriptions you made by hand.
- After 30 product pages, there are 30 timers and 30 cart listeners. Memory and CPU grow the longer the user shops. On a cheap phone, the page gets slower.
The fix:
import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
import { CartStore } from './cart.store';
@Component({
selector: 'app-sale-banner',
template: `<p>Sale ends in {{ secondsLeft() }} s. Cart: {{ cartCount() }}</p>`,
})
export class SaleBanner {
private readonly cartStore = inject(CartStore);
// toSignal unsubscribes when the component is destroyed.
private readonly tick = toSignal(interval(1000), { initialValue: 0 });
readonly secondsLeft = computed(() => Math.max(0, 600 - this.tick()));
readonly cartCount = toSignal(this.cartStore.count$, { initialValue: 0 });
}
- The toSignal function subscribes now and unsubscribes when the component is destroyed. It must be called in an injection context, like a field initializer.
- For a side effect without a value to show, use the takeUntilDestroyed operator in the constructor.
- In ngOnInit, takeUntilDestroyed needs a DestroyRef: inject DestroyRef in a field, and pass it in.
- A real sale should end at a time from the server. Counting ticks is only a demo; the browser may slow timers in background tabs.
Follow-up question: The same component also loads the product with HttpClient and subscribes without unsubscribing. Is that a leak too?
Follow-up answer:
- Usually not a long leak. An HttpClient request completes after one response, and a completed observable frees its subscriber.
- But if the user leaves before the response arrives, the callback still runs on a destroyed component. If it shows a message or starts navigation, the user sees something strange.
- Unsubscribing also cancels the HTTP request in the browser, which saves data on a slow phone.
- So the same rule is simple and safe: tie every subscription to the component’s life.
Red flag: Says “Angular cleans up subscriptions when the component is destroyed”. Angular only does this for the async pipe, toSignal and takeUntilDestroyed, not for a plain subscribe call.
2. A search box with subscribe inside subscribe
Question: This is the product search box of our online shop. The shop has about 50,000 products. Most users search on phones, often on a slow mobile network.
import { Component, OnInit, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { Product } from './product';
@Component({
selector: 'app-product-search',
imports: [ReactiveFormsModule],
template: `
<input [formControl]="query" placeholder="Search products" />
@for (p of results(); track p.id) {
<p>{{ p.name }}</p>
}
`,
})
export class ProductSearch implements OnInit {
private readonly http = inject(HttpClient);
readonly query = new FormControl('', { nonNullable: true });
readonly results = signal<Product[]>([]);
ngOnInit() {
this.query.valueChanges.subscribe(q => {
this.http.get<Product[]>(`/api/products?q=${q}`).subscribe(products => {
this.results.set(products);
});
});
}
}
You see this in code review. What do you think? Is there a problem?
Short answer: Each key press starts a new request, and the inner subscriptions are independent. Nothing cancels an old request, so responses can arrive out of order and an old answer can replace a newer one. Also: no debounce, no error handling, no unsubscribe, and the search text is put in the URL without encoding. The fix is one stream with debounceTime, distinctUntilChanged and switchMap, closed with toSignal or takeUntilDestroyed.
Hint (if the candidate says there is no problem): A user types “red shoes” quickly. The results list flickers, and at the end it shows results for “red sh”, not for “red shoes”. It happens more often on mobile than on office Wi-Fi.
Why does this happen? (step by step)
- The user types 9 characters, so valueChanges emits 9 times. The code sends 9 requests.
- The requests run in parallel. The server may answer short queries like “red sh” more slowly, because they match many more products.
- The response for “red shoes” arrives first and is shown. Then the slower response for “red sh” arrives and calls set again. The old result now covers the new one.
- Nothing links an answer to the query that is on the screen now. This is a race condition.
- On a slow network, response times vary more, so the wrong order happens more often.
- Extra problems: 9 requests for one search put load on the server. One failed request throws an error with no handler. The outer subscription is never closed. A query with “&” or “#” breaks the URL.
The fix:
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, debounceTime, distinctUntilChanged, map, of, switchMap } from 'rxjs';
import { Product } from './product';
@Component({
selector: 'app-product-search',
imports: [ReactiveFormsModule],
template: `
<input [formControl]="query" placeholder="Search products" />
@for (p of results(); track p.id) {
<p>{{ p.name }}</p>
}
`,
})
export class ProductSearch {
private readonly http = inject(HttpClient);
readonly query = new FormControl('', { nonNullable: true });
readonly results = toSignal(
this.query.valueChanges.pipe(
map(q => q.trim()),
debounceTime(300),
distinctUntilChanged(),
switchMap(q =>
q.length < 2
? of([])
: this.http.get<Product[]>('/api/products', { params: { q } }).pipe(
catchError(() => of([])),
),
),
),
{ initialValue: [] as Product[] },
);
}
- The debounceTime operator waits until the user stops typing for 300 ms. One search, not nine requests.
- The distinctUntilChanged operator skips a query that is the same as the one before.
- The switchMap operator unsubscribes from the old request when a new query arrives. HttpClient then cancels the old request. A late answer for an old query can never reach the screen.
- The catchError operator is inside switchMap. A failed request gives an empty list, and the search box keeps working.
- The params option encodes the text correctly.
- The toSignal function closes the subscription when the component is destroyed.
- The trade-off: debounce adds 300 ms before each search. Most shops accept that for far fewer requests.
Follow-up question: Why not mergeMap or concatMap here? And when is exhaustMap the right choice?
Follow-up answer:
- The mergeMap operator runs all requests in parallel and shows every answer in arrival order. That is the same race as the original code.
- The concatMap operator keeps the order but waits for each old request. The user waits for answers nobody needs anymore.
- In search, only the newest query matters, so switchMap is right.
- The exhaustMap operator ignores new values while one is running. It is right for a “Place order” button, so a double click does not send two orders. It would be wrong for search, because it would ignore the last letters the user typed.
Red flag: Says “the server answers in the order we send”. HTTP gives no such promise. Or fixes it only with debounceTime, which makes the race less common but does not remove it.
3. Filtering the product list in the template
Question: The category page of our online shop shows up to 5,000 products. The user can type in a filter box and pick a sort order. The app uses zone.js and the default change detection. The page also has a header with a cart badge and a chat widget that updates every few seconds.
import { Component, input, signal } from '@angular/core';
import { Product } from './product';
import { ProductRow } from './product-row';
@Component({
selector: 'app-category-page',
imports: [ProductRow],
template: `
<input (input)="term.set($any($event.target).value)" placeholder="Filter" />
<button (click)="sortByPrice.set(!sortByPrice())">Sort by price</button>
@for (p of visibleProducts(); track p.id) {
<app-product-row [product]="p" />
}
`,
})
export class CategoryPage {
readonly products = input.required<Product[]>();
readonly term = signal('');
readonly sortByPrice = signal(false);
visibleProducts(): Product[] {
const term = this.term().toLowerCase();
const list = this.products().filter(p => p.name.toLowerCase().includes(term));
return this.sortByPrice() ? list.sort((a, b) => a.price - b.price) : list;
}
}
You see this in code review. What do you think? Is there a problem?
Short answer: The visibleProducts method is called from the template, so it runs on every change detection check of this component, not only when the term, the sort or the products change. With zone.js and the default strategy, that is after every click, key press, timer and HTTP response anywhere in the app. Each run filters and sorts up to 5,000 items. The fix is a computed signal: it keeps the result and runs again only when a signal it reads changes.
Hint (if the candidate says there is no problem): On a mid-range phone, typing in the filter box feels slow, and even clicking “Add to cart” in the header feels slow. The performance panel shows visibleProducts in many long tasks, also when the user did not touch the filter.
Why does this happen? (step by step)
- Angular cannot know what a plain method returns without calling it. So on each check it calls visibleProducts again and compares the result.
- With zone.js and the default strategy, every event, timer and HTTP response starts a check of the whole tree. The chat widget’s timer alone starts one every few seconds.
- Each call reads 5,000 products, lowercases 5,000 names and makes a new array. With sorting on, it also sorts.
- In development mode, Angular runs a second check to catch changed values, so the method runs even more often.
- Interaction to Next Paint (INP) gets worse: the browser cannot paint the next frame until this work is done.
The fix:
import { Component, computed, input, signal } from '@angular/core';
import { Product } from './product';
import { ProductRow } from './product-row';
@Component({
selector: 'app-category-page',
imports: [ProductRow],
template: `
<input (input)="term.set($any($event.target).value)" placeholder="Filter" />
<button (click)="sortByPrice.set(!sortByPrice())">Sort by price</button>
@for (p of visibleProducts(); track p.id) {
<app-product-row [product]="p" />
}
`,
})
export class CategoryPage {
readonly products = input.required<Product[]>();
readonly term = signal('');
readonly sortByPrice = signal(false);
readonly visibleProducts = computed(() => {
const term = this.term().toLowerCase();
const list = this.products().filter(p => p.name.toLowerCase().includes(term));
return this.sortByPrice() ? list.sort((a, b) => a.price - b.price) : list;
});
}
- A computed signal remembers its last result. Reading it in the template is very cheap.
- It runs the filter again only when term, sortByPrice or products changes. A click in the header or a chat message does not cause any filtering.
- The template line is the same. Calling a signal in a template is fine, because a signal read is cheap.
- Adding OnPush (or a zoneless app) also helps: the component is checked less often. But the computed is the real fix, because it also stops repeat work inside each check.
- Sorting the result of filter is safe here, because filter always returns a new array. Sorting this.products() directly would change the parent’s input array.
- The trade-off: the computed keeps one more array in memory. That is small compared with the time saved.
Follow-up question: The filter still feels slow on each key press with 5,000 products. What else can you do?
Follow-up answer:
- Debounce the filter text, so the work runs after the user pauses, not on every key.
- Do not render 5,000 rows. Use pagination, “load more”, or virtual scrolling (the Angular CDK has a virtual scroll viewport), so only visible rows are in the DOM.
- Move the search to the server if the list can grow much bigger.
- Measure first with the browser performance panel. Often rendering the rows costs more than the filter itself.
Red flag: Says “Angular only calls the method when the data changes”. Or wants to fix it with a manual cache in a field that is easy to forget to clear.
4. An OnPush cart summary
Question: To make the product page faster, a teammate changed the cart summary to OnPush. The product page adds items to a local list and passes it down:
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
export interface CartItem {
productId: number;
name: string;
price: number;
quantity: number;
}
@Component({
selector: 'app-cart-summary',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [CurrencyPipe],
template: `<p>{{ items().length }} items, total {{ total() | currency }}</p>`,
})
export class CartSummary {
readonly items = input.required<CartItem[]>();
readonly total = computed(() => this.items().reduce((s, i) => s + i.price * i.quantity, 0));
}
@Component({
selector: 'app-product-page',
imports: [CartSummary],
template: `
<button (click)="addShoes()">Add shoes</button>
<app-cart-summary [items]="cartItems" />
`,
})
export class ProductPage {
cartItems: CartItem[] = [];
addShoes() {
this.cartItems.push({ productId: 7, name: 'Shoes', price: 50, quantity: 1 });
}
}
You see this in code review. What do you think? Is there a problem?
Short answer: The parent changes the same array with push. The reference does not change, so Angular sees the input as unchanged. The OnPush child is not marked dirty and is skipped, and its computed total keeps the old value too. The summary stays at “0 items”. The fix is to make a new array each time, or better, keep the cart in a signal and update it immutably.
Hint (if the candidate says there is no problem): Before the OnPush change, the item count updated. Now the button click works (a log in addShoes shows the array growing), but the summary text never changes. When something else later makes Angular check the summary, the item count suddenly jumps to the right number, but the total still does not change.
Why does this happen? (step by step)
- The click happens in the parent’s template, so Angular checks the parent.
- While checking the parent, Angular evaluates the binding for the items input. It gets the same array object as last time.
- Angular compares the old and new input values by reference, like ===. Same object means “no change”. The input is not set again.
- An OnPush component is only checked when it is marked dirty: a new input reference, an event in its own template, the async pipe, or a signal it reads in its template. None of these happened. So Angular skips it.
- The input signal also did not change, so the computed total is not computed again. It keeps its cached value.
- Before, with the default strategy, Angular checked the child anyway and read items().length from the changed array. That is why the count “worked”. The computed total was already stale then. The bug was always there; OnPush made it easier to see.
The fix:
import { Component, signal } from '@angular/core';
import { CartItem, CartSummary } from './cart-summary';
@Component({
selector: 'app-product-page',
imports: [CartSummary],
template: `
<button (click)="addShoes()">Add shoes</button>
<app-cart-summary [items]="cartItems()" />
`,
})
export class ProductPage {
readonly cartItems = signal<CartItem[]>([]);
addShoes() {
// A new array: the input reference changes, so the child is marked dirty.
this.cartItems.update(items => [...items, { productId: 7, name: 'Shoes', price: 50, quantity: 1 }]);
}
}
- The update method returns a new array. The child sees a new reference and is checked.
- The child’s computed total also runs again, because its input signal changed.
- If a quantity changes, make a new item object too, not only a new array. Otherwise a child that tracks the item reference misses the change.
- In a real shop, the cart is shared state, so it belongs in a root CartService with a signal. Then the summary can read the service directly.
- The trade-off: copying arrays costs a little memory and time. For a cart with a few dozen lines, this is tiny. Detecting changes deep inside a big object on every check costs much more.
Follow-up question: Someone suggests calling markForCheck in the parent after push, or switching the child back to the default strategy. What do you think?
Follow-up answer:
- The markForCheck method marks the component it is called on and its ancestors, not its children. Calling it in the parent does not mark the OnPush child. It would have to be called inside the child, which knows nothing about the push.
- Even if the child is checked, its computed total does not run again, because the input signal did not change. So total shows the old value.
- Going back to the default strategy makes the count update again, but the computed total is still stale.
- The real fix is immutable updates. They work with OnPush, with signals and with zoneless apps.
Red flag: Says “OnPush is broken, turn it off”. Or calls detectChanges in many places to force updates instead of fixing how data changes.
5. Keeping the cart total in sync with an effect
Question: This is the cart service of our online shop. Orders of 100 euros or more get free shipping. The checkout page also has a button that adds shipping insurance and sends the new total to analytics.
import { Injectable, effect, signal } from '@angular/core';
export interface CartItem {
productId: number;
price: number;
quantity: number;
}
@Injectable({ providedIn: 'root' })
export class CartService {
readonly items = signal<CartItem[]>([]);
readonly total = signal(0);
readonly freeShipping = signal(false);
constructor() {
effect(() => {
const total = this.items().reduce((s, i) => s + i.price * i.quantity, 0);
this.total.set(total);
this.freeShipping.set(total >= 100);
});
}
add(item: CartItem) {
this.items.update(items => [...items, item]);
}
}
// In the checkout component
addInsurance() {
this.cart.add({ productId: 999, price: 5, quantity: 1 });
this.analytics.track('cart-total', this.cart.total());
}
You see this in code review. What do you think? Is there a problem?
Short answer: The effect copies derived state into other signals. Effects do not run right away; Angular runs them later. So right after add, total and freeShipping still have the old values, and analytics gets the old total. Also anyone can call total.set and break it. Values derived from other signals should be computed signals: always correct, lazy, cached and read-only.
Hint (if the candidate says there is no problem): The analytics team says the “cart-total” event is always one step behind: after adding insurance to a 40 euro cart, it reports 40, not 45. On the page, the total looks right a moment later.
Why does this happen? (step by step)
- The add method sets items. That only marks the effect as “needs to run”. The effect does not run inside add.
- Angular runs effects later, as part of its change detection work. So the code after add still runs first.
- The next line reads total(). The effect has not run yet, so total still holds the old sum. Analytics gets 40.
- A moment later the effect runs and sets total to 45. The page shows 45, so in manual testing everything looks fine.
- Any other code that reads total or freeShipping between the change and the effect gets wrong data. For example, a guard that checks freeShipping before navigation.
- The total is a writable signal. Any code can call total.set(0), and the cart and the total no longer match.
- Each change does extra work: the effect runs, writes two signals, and those writes can cause another round of updates.
The fix:
import { Injectable, computed, signal } from '@angular/core';
export interface CartItem {
productId: number;
price: number;
quantity: number;
}
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly lines = signal<CartItem[]>([]);
readonly items = this.lines.asReadonly();
readonly total = computed(() => this.lines().reduce((s, i) => s + i.price * i.quantity, 0));
readonly freeShipping = computed(() => this.total() >= 100);
add(item: CartItem) {
this.lines.update(items => [...items, item]);
}
}
- A computed is always correct when you read it. If items changed, it computes again right at that read. So analytics now gets 45.
- It is cached. Many reads cost almost nothing until items changes again.
- It is read-only. Nobody can set total to a wrong value.
- The items list is also exposed read-only, so only the service changes the cart.
- Use effect only for side effects that leave the signal world: saving the cart to localStorage, logging, drawing on a canvas, calling a non-Angular library.
- Angular allows writing signals inside an effect, but that is a sign the value should probably be a computed or a linkedSignal.
Follow-up question: The checkout has a shipping method picker. By default it should be “free” when freeShipping is true and “standard” otherwise. The user can pick “express”. If the cart changes and crosses 100 euros, the default should apply again. Computed or effect?
Follow-up answer:
- Neither is a good fit. A computed cannot be set by the user. An effect has the same problems as above.
- The linkedSignal function is made for this: a writable signal whose value is reset from a source when the source changes.
readonly shipping = linkedSignal<'free' | 'standard' | 'express'>(
() => (this.freeShipping() ? 'free' : 'standard'),
);
chooseExpress() {
this.shipping.set('express');
}
- The user can set it. When freeShipping changes, the value is computed again from the source and the user’s choice is replaced.
- If you need to keep the user’s choice when it is still valid, linkedSignal also has a form with source and computation, where the computation gets the previous value.
Red flag: Says “an effect is just like a watcher, it is the normal way to keep values in sync”. Or does not know that effects run later, not inside the set call.
6. The cart list with track $index
Question: The cart page lists the cart lines. Each line is a component with a “gift message” text box and an “open details” toggle that the line keeps in its own signals. The user can sort the cart by price and remove lines.
<!-- cart-page template -->
@for (line of sortedLines(); track $index) {
<app-cart-line [line]="line" (remove)="cart.remove(line.productId)" />
}
import { Component, input, output, signal } from '@angular/core';
import { CartItem } from './cart.service';
@Component({
selector: 'app-cart-line',
template: `
<h3>{{ line().name }}</h3>
<button (click)="open.set(!open())">Details</button>
@if (open()) {
<textarea placeholder="Gift message" (input)="giftMessage.set($any($event.target).value)"></textarea>
}
<button (click)="remove.emit()">Remove</button>
`,
})
export class CartLine {
readonly line = input.required<CartItem>();
readonly remove = output<void>();
readonly open = signal(false);
readonly giftMessage = signal('');
}
You see this in code review. What do you think? Is there a problem?
Short answer: With track $index, Angular thinks “row 0 is always the same item”. When the list is sorted or a line is removed, it does not move the components. It keeps each component at its position and only gives it a new line input. The local state (open details, the gift message, focus) stays at the position and now belongs to a different product. The fix is to track by a stable id: track line.productId.
Hint (if the candidate says there is no problem): A user writes a gift message on the “Shoes” line, then removes the “Hat” line above it. Now the gift message box is open on a different product. Sorting by price shows the same problem.
Why does this happen? (step by step)
- The track expression tells Angular how to match old rows with new rows. With $index, row identity is the position.
- Say the cart is Hat, Shoes, Scarf. The user opens details on Shoes (position 1) and types a message.
- The user removes Hat. The new list is Shoes, Scarf.
- Angular matches by position: position 0 and 1 still exist, position 2 is gone. So it keeps the first two components, gives them new line inputs, and destroys the last component.
- The component at position 0 used to show Hat. It now shows Shoes, with Hat’s closed details.
- The component at position 1 used to show Shoes. It now shows Scarf, but its open signal is still true and its giftMessage is still the Shoes message.
- The last component, which showed Scarf, is destroyed. The user’s Shoes message now sits on the Scarf line.
- Angular also updates the bindings of every row instead of removing one row, so it does more DOM work than needed.
The fix:
@for (line of sortedLines(); track line.productId) {
<app-cart-line [line]="line" (remove)="cart.remove(line.productId)" />
} @empty {
<p>Your cart is empty.</p>
}
- Now identity is the product id. When Hat is removed, Angular destroys only the Hat component.
- When the list is sorted, Angular moves the existing DOM nodes and components. Each component keeps its own state.
- Pick a key that is unique and stable for the life of the item, usually the id from the database.
- track $index is fine for a static list that is never reordered and has no local state, like a list of size labels.
Follow-up question: Why not track line, the object itself? It is unique.
Follow-up answer:
- Tracking by object reference works only while the objects stay the same.
- In a signal-based cart, a changed line becomes a new object, and data from the server gives new objects on every load.
- Then those items look new. Angular destroys and recreates their rows and components, and their local state is lost.
- An id from the data is stable across reloads and immutable updates, so it is the safe default.
Red flag: Says “track is only for performance, it does not change behavior”. With components that have their own state, the wrong track changes what the user sees.
7. The cart service in a component's providers
Question: A new developer built the product list page. The cart service already existed. Here is the service and the new page:
import { Injectable, computed, signal } from '@angular/core';
export interface CartItem {
productId: number;
price: number;
quantity: number;
}
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly lines = signal<CartItem[]>([]);
readonly items = this.lines.asReadonly();
readonly count = computed(() => this.lines().reduce((n, i) => n + i.quantity, 0));
add(item: CartItem) {
this.lines.update(items => [...items, item]);
}
}
import { Component, inject } from '@angular/core';
import { CartService } from './cart.service';
import { ProductCard } from './product-card';
import { CatalogService } from './catalog.service';
@Component({
selector: 'app-product-list-page',
imports: [ProductCard],
providers: [CartService],
template: `
@for (p of catalog.products(); track p.id) {
<app-product-card [product]="p" (add)="cart.add({ productId: p.id, price: p.price, quantity: 1 })" />
}
`,
})
export class ProductListPage {
protected readonly cart = inject(CartService);
protected readonly catalog = inject(CatalogService);
}
The header and the cart page also inject CartService. You see this in code review. What do you think? Is there a problem?
Short answer: Listing CartService in the page’s providers array creates a second, separate CartService for this page and its children. The page adds items to its own private cart. The header and the cart page use the root instance, which stays empty. When the user leaves the page, the component is destroyed and its cart instance with it. The fix is to remove CartService from the providers array, so everyone gets the one root instance.
Hint (if the candidate says there is no problem): Users add three products, but the header badge still says 0. When they open the cart page, it is empty. If they go back to the product list, it also starts with an empty cart.
Why does this happen? (step by step)
- The providedIn root option registers one CartService in the root injector. That is the instance the header and the cart page get.
- The providers array of a component creates a new injector for that component. Angular makes a new CartService for each instance of ProductListPage.
- When a component calls inject, Angular first looks in the component’s own injector, then in its parents, and only at the end in the root. The first match wins.
- So ProductListPage and its children find the local CartService first. They never reach the root one.
- The header is not a child of the page, so it gets the root instance. The two carts never share data.
- When the router leaves the page, the component is destroyed. Its injector and its CartService are destroyed too. The items are gone.
- Coming back to the page creates a new component with a new, empty CartService.
The fix:
@Component({
selector: 'app-product-list-page',
imports: [ProductCard],
// No providers: inject finds the root CartService.
template: `
@for (p of catalog.products(); track p.id) {
<app-product-card [product]="p" (add)="cart.add({ productId: p.id, price: p.price, quantity: 1 })" />
}
`,
})
export class ProductListPage {
protected readonly cart = inject(CartService);
protected readonly catalog = inject(CatalogService);
}
- With providedIn root, you do not list the service anywhere. The inject function finds it.
- Shared app state (cart, signed-in user, settings) should have exactly one instance: providedIn root.
- A code review rule helps: a service with providedIn root should not appear in a providers array unless there is a clear reason written in a comment.
Follow-up question: When is a service in a component’s providers the right choice?
Follow-up answer:
- When each instance of the component needs its own state. For example, the product page has two image galleries, and each one has its own selected image. A GalleryState in the gallery component’s providers gives each gallery its own instance.
- Another example: a multi-step checkout form whose draft state should be thrown away when the user leaves the checkout.
- The instance lives exactly as long as the component. If the service has an ngOnDestroy method, Angular calls it when the component is destroyed. That is a good place to clean up.
- Such a service usually has a plain Injectable decorator without providedIn, so nobody uses it by mistake as a global singleton.
Red flag: Says “providers is needed so the component can inject the service”. With providedIn root it is not needed, and adding it changes the behavior.
8. Today's offers with two async pipes
Question: The home page of our online shop shows “today’s offers”. The list comes from an API that is slow (about 800 ms) because it computes prices for each user. The home page is the most visited page.
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Product } from './product';
@Component({
selector: 'app-todays-offers',
imports: [AsyncPipe],
template: `
<h2>Today's offers ({{ (offers$ | async)?.length ?? 0 }})</h2>
@for (p of offers$ | async; track p.id) {
<p>{{ p.name }}</p>
}
`,
})
export class TodaysOffers {
private readonly http = inject(HttpClient);
readonly offers$ = this.http.get<Product[]>('/api/offers/today');
}
You see this in code review. What do you think? Is there a problem?
Short answer: HttpClient returns a cold observable: each subscription runs the request again. The template has two async pipes, so it subscribes twice and sends two identical requests. That doubles the load on a slow, expensive endpoint, and the heading and the list can even show different data. The fix is to subscribe once, for example with toSignal, and read the result in both places.
Hint (if the candidate says there is no problem): The backend team sees exactly twice as many calls to the offers endpoint as home page views. In the browser network tab, each home page load shows two requests to the same URL.
Why does this happen? (step by step)
- The get method does not send anything. It returns a description of the request: a cold observable.
- Each subscribe runs that description from the start. One subscribe, one request.
- Each async pipe subscribes on its own. Two pipes mean two subscriptions, so two requests.
- The two answers can arrive at different times. For a moment the heading can show a count while the list is still empty.
- If prices change between the two calls, the heading and the list can disagree.
- Adding a third place that shows offers would add a third request. The cost grows silently.
The fix:
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
import { Product } from './product';
@Component({
selector: 'app-todays-offers',
template: `
<h2>Today's offers ({{ offers().length }})</h2>
@for (p of offers(); track p.id) {
<p>{{ p.name }}</p>
}
`,
})
export class TodaysOffers {
private readonly http = inject(HttpClient);
// One subscription: the template reads the signal many times.
readonly offers = toSignal(this.http.get<Product[]>('/api/offers/today'), {
initialValue: [] as Product[],
});
}
- The toSignal function subscribes once. The template reads the signal in two places, which costs nothing extra.
- It unsubscribes when the component is destroyed.
- Another option is one async pipe with an alias: an @if block around the whole part reads the observable once with the async pipe and gives the result a name. The heading and the list then use that name.
- The trade-off with an initial empty list: the user briefly sees “0” before the data arrives. In a real page, show a loading state instead.
Follow-up question: Now the header also shows “3 offers today” and a sidebar shows the first offer. Three components need the same data. How do you avoid three requests?
Follow-up answer:
- Move the request into a root service, so all components share one source.
- One way: shareReplay with bufferSize 1 and refCount true. The first subscriber starts the request; the others get the same response. Because an HTTP observable completes, the response then stays cached for the life of the service, which is the whole session. refCount true only matters while the request is still running: if every subscriber leaves, the request is cancelled.
@Injectable({ providedIn: 'root' })
export class OffersService {
private readonly http = inject(HttpClient);
readonly offers$ = this.http
.get<Product[]>('/api/offers/today')
.pipe(shareReplay({ bufferSize: 1, refCount: true }));
}
- Another way: the service loads once into a signal, and components read the signal.
- Either way, decide how fresh the data must be. Offers change daily, so caching them for one session is usually fine. A stock count needs a way to reload, for example a refresh trigger that starts a new request.
Red flag: Says “the browser caches the second GET, so it is free”. HTTP caching depends on server headers, and a personalized response is usually not cacheable. Or does not know that HttpClient observables are cold.
9. Showing the seller's product description
Question: Our online shop became a marketplace. About 2,000 sellers write their own product descriptions in a rich text editor. The server saves the HTML as it is, and the product page shows it. At first, Angular removed some of the formatting and printed a warning in the console, so a developer changed the component to this:
import { Component, computed, inject, input } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'app-product-description',
template: `<div class="description" [innerHTML]="descriptionHtml()"></div>`,
})
export class ProductDescription {
private readonly sanitizer = inject(DomSanitizer);
readonly html = input.required<string>(); // written by the seller
// Angular removed parts of the HTML, so we mark it as trusted.
readonly descriptionHtml = computed(() => this.sanitizer.bypassSecurityTrustHtml(this.html()));
}
You see this in code review. What do you think? Is there a problem?
Short answer: This is a stored XSS hole. By default Angular sanitizes values bound to innerHTML: it removes script tags, event handler attributes like onerror, and javascript: URLs. The bypassSecurityTrustHtml method turns that protection off. Any seller, or anyone who takes over a seller account, can save HTML that runs JavaScript in every customer’s browser on our domain. The fix is to remove the bypass and let Angular sanitize, and to also clean the HTML on the server with an allowlist when it is saved.
Hint (if the candidate says there is no problem): A security researcher sends us a product link. When a signed-in customer opens it, the customer’s account email is changed without any click. The product description contains only an image.
Why does this happen? (step by step)
- A seller saves this description: an img tag with a broken src and an onerror attribute that runs JavaScript.
- The server stores it as it is. The API sends it to every customer who opens the product.
- Without the bypass, Angular would strip the onerror attribute before putting the HTML in the page.
- With the bypass, Angular puts the HTML in the page unchanged. The image fails to load, and the browser runs the onerror code.
- The code runs on our origin, with the customer’s session. It can read data in localStorage (like a login token), call our API as the customer, change the address or email, or show a fake payment form.
- It is “stored” XSS: the attacker saves it once, and it runs for every visitor. It does not need a script tag; event attributes are enough.
- The comment “we mark it as trusted” is the real mistake. The HTML comes from users, so it is the opposite of trusted.
The fix:
import { Component, input } from '@angular/core';
@Component({
selector: 'app-product-description',
// Angular sanitizes values bound to innerHTML.
template: `<div class="description" [innerHTML]="html()"></div>`,
})
export class ProductDescription {
readonly html = input.required<string>(); // written by the seller
}
- Bind the raw string. Angular’s sanitizer keeps safe formatting (paragraphs, lists, bold, links) and removes dangerous parts.
- Also sanitize on the server when the seller saves, with an allowlist of tags and attributes. Then other clients, like the mobile app or emails, are safe too.
- Even better for a marketplace: let sellers write Markdown or use an editor that stores a structured format, and render only the elements you allow.
- Add a Content Security Policy as a second layer, so inline scripts and unknown script sources are blocked even if a hole slips through.
- If the missing formatting matters, add it the safe way: style the allowed tags with CSS in the description container.
- Use the bypass methods only for values your own code builds from known parts, never for user input.
Follow-up question: Sellers now want to embed a YouTube video in the description. How do you allow this safely?
Follow-up answer:
- Do not allow iframe tags in the seller HTML.
- Add a separate “video” field. The seller pastes a link; the server extracts the video id and checks it with a strict pattern (letters, digits, dash and underscore only).
- The client builds the embed URL itself from a fixed YouTube embed address plus the checked id. Only this URL, built by our code, is marked as a trusted resource URL with bypassSecurityTrustResourceUrl.
- The CSP frame-src rule allows only the YouTube embed domain.
- So the seller controls only an id, never HTML or a full URL.
Red flag: Says “only our sellers can write descriptions, so it is safe”, or “we use HTTPS”. Or thinks XSS needs a script tag, and that removing script tags is enough.
10. A cart store that changes its object
Question: This is the cart store of our online shop. The header badge shows count(), and the cart page shows the lines and total().
import { Injectable, computed, signal } from '@angular/core';
export interface CartLine {
productId: number;
price: number;
quantity: number;
}
export interface Cart {
lines: CartLine[];
}
@Injectable({ providedIn: 'root' })
export class CartStore {
readonly cart = signal<Cart>({ lines: [] });
readonly count = computed(() => this.cart().lines.reduce((n, l) => n + l.quantity, 0));
readonly total = computed(() => this.cart().lines.reduce((s, l) => s + l.price * l.quantity, 0));
add(productId: number, price: number) {
const cart = this.cart();
const line = cart.lines.find(l => l.productId === productId);
if (line) {
line.quantity++;
} else {
cart.lines.push({ productId, price, quantity: 1 });
}
this.cart.set(cart);
}
clear() {
this.cart.set({ lines: [] });
}
}
You see this in code review. What do you think? Is there a problem?
Short answer: The add method changes the cart object in place and then sets the same object again. A signal compares the new value with the old one using Object.is. Same reference means “no change”, so the signal tells nobody. The count and total computed signals keep their cached values, and the views that read them are not updated. The fix is to treat state as immutable: build a new cart object (and new arrays and lines) in update.
Hint (if the candidate says there is no problem): Users click “Add to cart” and the badge stays at 0. Later, when the cart is loaded again from the server (a new object), the badge suddenly shows the right number. Unit tests that read cart().lines directly pass.
Why does this happen? (step by step)
- Reading the cart signal returns the current object. The code changes its lines array and a line inside it. That changes the object, but the signal is not told.
- The set call then gives the signal the same object. By default a signal compares with Object.is, and an object is always equal to itself.
- The signal decides the value did not change. It does not notify computed signals or templates.
- The count computed is cached. It only computes again when a signal it depends on notifies a change. So it returns the old count.
- Templates that read count() are not marked for refresh. With OnPush or a zoneless app, nothing updates.
- A test that reads cart().lines sees the new data, because the object really changed. That is why tests pass.
- When another code path sets a new object, the computed runs again and reads the changed lines. The badge “catches up” all at once.
The fix:
add(productId: number, price: number) {
this.cart.update(cart => {
const exists = cart.lines.some(l => l.productId === productId);
const lines = exists
? cart.lines.map(l => (l.productId === productId ? { ...l, quantity: l.quantity + 1 } : l))
: [...cart.lines, { productId, price, quantity: 1 }];
return { ...cart, lines };
});
}
- The update method gets the current value and must return the next value.
- We return a new cart object with a new lines array. The changed line is a new object too, and unchanged lines are reused.
- Object.is now sees a different reference, so the signal notifies. The count and total signals compute again, and the views update.
- Reusing unchanged lines helps a list tracked by id: only the changed row updates.
- To stop this bug from coming back, expose only a read-only signal (with asReadonly) and use readonly types, so other code cannot change the object.
private readonly state = signal<Cart>({ lines: [] });
readonly cart = this.state.asReadonly();
- The trade-off: each change copies one array and one line. For a cart this is very cheap.
Follow-up question: A teammate says: “Just create the signal with an equal function that always returns false. Then set always notifies.” Is that a good fix?
Follow-up answer:
- It works in this narrow case: signal accepts an equal option, and if it always returns false, every set notifies.
- But it hides the real problem. The object is still changed in place, so anyone who kept the old reference sees it change under them.
- Anything that compares old and new values breaks: an “undo” feature, a linkedSignal that looks at the previous value, an OnPush child that gets cart.lines as an input. The array reference is the same, so the child is still skipped.
- Every set now notifies, even when nothing changed, which causes extra work.
- Immutable updates are the expected model for signals. Use a custom equal only for real value equality, for example to compare two filter objects by their fields.
Red flag: Says “set always triggers an update”. Or fixes it by calling detectChanges or markForCheck by hand after each add.
11. The routes file of a growing shop
Question: Our online shop is a client-rendered Angular app. About 70% of visitors use mid-range Android phones on mobile networks. The admin dashboard uses a large chart library, and only about 20 staff members use it. The product page shows a store availability map (from a map library) at the bottom. Here is the routes file:
import { Routes } from '@angular/router';
import { adminGuard } from './admin/admin.guard';
import { Home } from './home/home';
import { ProductList } from './products/product-list';
import { ProductPage } from './products/product-page';
import { CartPage } from './cart/cart-page';
import { Checkout } from './checkout/checkout';
import { Account } from './account/account';
import { AdminDashboard } from './admin/admin-dashboard';
export const routes: Routes = [
{ path: '', component: Home },
{ path: 'products', component: ProductList },
{ path: 'products/:id', component: ProductPage },
{ path: 'cart', component: CartPage },
{ path: 'checkout', component: Checkout },
{ path: 'account', component: Account },
{ path: 'admin', component: AdminDashboard, canActivate: [adminGuard] },
];
You see this in code review. What do you think? Is there a problem?
Short answer: Every page is imported statically, so the bundler puts all of them, with the chart library and the map library, in the initial bundle. Every visitor downloads, parses and runs code for checkout, account and the admin dashboard before the home page can render. On mid-range phones this is slow, so LCP and INP suffer. The fix: lazy routes with loadComponent (and loadChildren with canMatch for admin), @defer for heavy parts inside a page, and a size budget so it does not grow back.
Hint (if the candidate says there is no problem): Field data shows the home page LCP at the 75th percentile is 4.8 s on phones (good is 2.5 s or less). The build output says the initial bundle is about 1.9 MB before compression. The bundle analyzer shows the chart library as one of the biggest parts.
Why does this happen? (step by step)
- A static import at the top of a file tells the bundler “this code is needed to start”. So every page component and everything it imports goes into the initial bundle.
- The canActivate guard runs only when someone navigates to admin. It blocks the navigation, not the download. The chart library is already in every customer’s browser.
- On a phone, the cost is not only download time. The CPU must parse, compile and run the JavaScript. Mid-range phones are several times slower at this than a developer laptop.
- In a client-rendered app, the main content appears only after Angular starts and renders the home page. A big bundle delays that, so LCP gets worse.
- While the main thread is busy with this work, taps are not handled, so the first interactions feel slow too.
- The problem grows quietly: each new page or library adds to the start-up cost for everyone.
The fix:
import { Routes } from '@angular/router';
import { adminGuard } from './admin/admin.guard';
import { Home } from './home/home';
export const routes: Routes = [
{ path: '', component: Home }, // the landing page stays eager
{ path: 'products', loadComponent: () => import('./products/product-list').then(m => m.ProductList) },
{ path: 'products/:id', loadComponent: () => import('./products/product-page').then(m => m.ProductPage) },
{ path: 'cart', loadComponent: () => import('./cart/cart-page').then(m => m.CartPage) },
{ path: 'checkout', loadComponent: () => import('./checkout/checkout').then(m => m.Checkout) },
{ path: 'account', loadComponent: () => import('./account/account').then(m => m.Account) },
{
path: 'admin',
canMatch: [adminGuard], // if it fails, the admin code is not loaded
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];
Inside the product page, the map is below the fold, so it can wait:
@defer (on viewport) {
<app-store-map [productId]="product().id" />
} @placeholder {
<div class="map-box">Store availability</div>
}
- With loadComponent, each page becomes its own chunk, downloaded only when the user goes there.
- The admin area gets its own routes file. With canMatch, the router does not even match the route for non-admins, so their browsers never download the admin code.
- With @defer, the map component and its library are loaded only when the placeholder comes near the screen. Give the placeholder the same size as the map, so the page does not jump (CLS).
- Check that nothing else imports these components or libraries statically, for example a shared service that imports the chart library. That would pull them back into the initial bundle.
- Add a budget in angular.json, so the build warns or fails when the initial bundle grows:
"budgets": [
{ "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" }
]
- Measure before and after: build size, Lighthouse in the lab, and real user LCP and INP at the 75th percentile.
- The trade-off: the first visit to a lazy page waits for a small download. The next question deals with that.
Follow-up question: After the change, the home page is fast, but opening a product page on a slow network now shows a short delay. What can you do?
Follow-up answer:
- Preload lazy routes after the app has started. The router has preloading strategies; PreloadAllModules, set with withPreloading in provideRouter, downloads all lazy routes in the background after the first navigation.
- Loading everything costs mobile data, and it would also download the admin code for every customer. A custom preloading strategy can load only the likely next pages, like the product page and the cart, and never admin.
- For @defer blocks, you can prefetch earlier than you render, for example: on viewport for rendering and prefetch on idle.
- Server-side rendering with hydration can also make the first paint faster, because the HTML arrives ready. It is a bigger change, so measure first.
Red flag: Says “the guard protects admin, so its code is not loaded”. Or wants to fix it only with a CDN or better compression, without reducing the JavaScript that phones must run.
12. Designing state for the order admin dashboard
Question: Design the state for the order admin dashboard of our online shop. About 50 staff members use it. The shop gets about 2,000 orders a day. The dashboard has:
- A table of orders, 50 per page, with filters (status, search by customer or order number), sorting and pages.
- Tabs with the number of orders in each status.
- A side panel with the details of one order.
- Checkboxes and a bulk action “mark as shipped”.
- Staff often send each other links like “all paid orders that are not shipped yet”. The browser back button must work.
- Several staff members work on the same orders at the same time.
Where does each piece of state live? Would you use services with signals or a store library like NgRx SignalStore? Explain your design step by step.
Short answer: First split the state by kind. Filters, sort, page and the open order id live in the URL query string, which is the source of truth. Server data (order pages, counts, details) is loaded from those filters with switchMap and refreshed after changes. Local UI state (checked rows) lives in signals in the feature. App-wide state (the signed-in user and permissions) lives in a root service. For one dashboard, a feature-level service with signals is enough. A store library like NgRx SignalStore pays off when many features and developers need the same structure.
The kinds of state:
- URL state: status, search text, sort, page, the open order id. It must survive a reload, work with the back button, and be shareable as a link. So the URL is its home, not a copy in memory.
- Server state: order rows, the counts per status, the details of one order. The server owns it. The client only has a cached copy that can be stale.
- Local UI state: checked rows, an open dropdown. It belongs to this screen only and can be lost when the user leaves.
- App state: the signed-in user and their permissions. A root service, shared by the whole app.
A design with a feature service and signals:
import { Injectable, computed, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, of, switchMap, tap } from 'rxjs';
export type OrderStatus = 'all' | 'new' | 'paid' | 'shipped' | 'cancelled';
const STATUSES: OrderStatus[] = ['all', 'new', 'paid', 'shipped', 'cancelled'];
export interface OrderFilters { status: OrderStatus; q: string; page: number; }
export interface OrderRow { id: string; customer: string; total: number; status: OrderStatus; }
export interface OrderPage { rows: OrderRow[]; totalCount: number; }
const EMPTY_PAGE: OrderPage = { rows: [], totalCount: 0 };
@Injectable() // listed in the orders page component's providers
export class OrdersStore {
private readonly http = inject(HttpClient);
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
// 1. URL state: the query string is the source of truth.
private readonly params = toSignal(this.route.queryParamMap, { requireSync: true });
readonly filters = computed<OrderFilters>(() => {
const p = this.params();
const status = p.get('status') as OrderStatus;
return {
status: STATUSES.includes(status) ? status : 'all',
q: p.get('q') ?? '',
page: Math.max(1, Number(p.get('page')) || 1),
};
});
// 2. Server state: load again when the filters change or after a reload.
private readonly reloads = signal(0);
readonly loading = signal(false);
readonly error = signal(false);
readonly page = toSignal(
toObservable(computed(() => ({ filters: this.filters(), reload: this.reloads() }))).pipe(
tap(() => {
this.loading.set(true);
this.error.set(false);
}),
switchMap(({ filters }) =>
this.http.get<OrderPage>('/api/admin/orders', { params: { ...filters } }).pipe(
catchError(() => {
this.error.set(true);
return of(EMPTY_PAGE);
}),
),
),
tap(() => this.loading.set(false)),
),
{ initialValue: EMPTY_PAGE },
);
// 3. Local UI state.
readonly selected = signal<ReadonlySet<string>>(new Set());
setFilters(change: Partial<OrderFilters>) {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { ...change, page: change.page ?? 1 },
queryParamsHandling: 'merge',
});
}
markShipped(ids: string[]) {
this.http.post('/api/admin/orders/ship', { ids }).subscribe({
next: () => {
this.selected.set(new Set());
this.reloads.update(n => n + 1);
},
error: () => this.error.set(true),
});
}
}
- A filter change only updates the URL. The URL change flows into filters, and the filters start a new request. There is one direction of data, so the URL and the table can never disagree.
- Values from the URL are checked. A broken link falls back to safe defaults.
- The switchMap operator cancels an old request when the filters change quickly, so an old page never replaces a new one.
- A changed filter sends the user back to page 1.
- The store is listed in the orders page component’s providers. It lives as long as the page, and the checked rows are cleared when the user leaves.
- After a bulk action, the store loads the page again from the server instead of guessing the new state on the client. The server applies the business rules.
- The tabs with counts can use a second request in the same style, refreshed on the same reload signal.
Fresh data with many staff members:
- Reload when the browser tab gets focus again, and refresh the counts every 30 to 60 seconds. If staff need live updates, the server can push events (Server-Sent Events or WebSocket).
- The server checks every change. Shipping a cancelled order must fail. Each order can have a version number; an update with an old version gets a 409 Conflict, and the panel shows “this order was changed by someone else” and loads it again.
Services with signals or a store library?
- Services with signals are enough for one dashboard: no extra dependency, and every Angular developer can read them. The risk is that each team builds its own pattern.
- NgRx SignalStore gives one shared structure for state, computed values and methods (signalStore with withState, withComputed and withMethods), helpers for collections of entities, and rxMethod for RxJS pipelines like the loading above. It is worth it when many features and developers should write state the same way.
- The classic NgRx Store (actions, reducers, effects) suits very large apps where many features react to the same events or where the team wants Redux DevTools with a full event log. It costs more code for each feature.
- The design above maps well to SignalStore later. The big decisions (URL as the source of truth, server data loaded from filters, local UI state kept local) stay the same.
- Angular also has resource and httpResource for loading server data into signals. They are experimental, so this design does not depend on them.
Follow-up question: Staff complain: “I filtered, opened an order, closed the panel, and lost my scroll position and my checked rows.” How do you change the design?
Follow-up answer:
- The open order id goes in the URL too (for example a query parameter “order”). Opening the panel only adds that parameter; the table stays on the screen and is not loaded again, because the filters did not change.
- Make sure opening and closing the panel does not destroy the table component. Then its scroll position stays.
- Checked rows stay in the store as long as the page lives. Decide what happens when the filters change: usually clear them, because checked rows that are no longer visible are dangerous with bulk actions.
- Restoring scroll on back navigation is possible with the router’s scroll position restoration option, but for a panel on the same page, not destroying the table is simpler.
Red flag: Keeps the filters only in memory, so links cannot be shared and the back button breaks. Or puts everything, including form input text and checked rows, in one global store that lives forever. Or never refreshes server data and trusts the client to decide if an order can be shipped.
13. The coupon check on every key
Question: This is part of our checkout form:
form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
coupon: ['', [], [this.couponValidator]],
});
couponValidator = (c: AbstractControl) =>
this.api.check(c.value).pipe(
map((ok) => (ok ? null : { badCoupon: true })),
);
<input formControlName="coupon" />
@if (form.controls.coupon.invalid) {
<p class="error">This coupon does not work.</p>
}
<button (click)="pay()">Pay</button>
What do you think? Is there a problem?
Short answer: Three problems. The async validator sends a request on every key press, because nothing waits until typing stops. The error shows as soon as the value is invalid, even before the user has left the field. And pay() can run while the check is still PENDING, or twice on a double click. Wait with timer plus switchMap inside the validator (or use updateOn: ‘blur’), show the error only after touched, and block submit while the form is pending or saving. Also handle server errors in the validator, and validate the coupon again on the server.
Hint (if the candidate says there is no problem): A customer types a 10-letter coupon. The network tab shows 10 requests to /api/coupons/check. One customer said: “it said my coupon is wrong while I was still typing it”.
Why does this happen? (step by step)
- Every value change runs the validators. Async validators run after the sync ones pass, so on every key.
- Angular cancels the previous async check, but the request has already been sent to the server.
- While the request runs, the status is PENDING. When the answer for a half-typed code comes, the control is INVALID, and the template shows the error at once.
- If the API call fails, the observable errors and the control stays in a bad state.
- The button does not look at pending or at a saving flag.
The fix:
couponValidator: AsyncValidatorFn = (c) =>
timer(400).pipe(
switchMap(() => this.api.check(c.value)),
map((ok) => (ok ? null : { badCoupon: true })),
catchError(() => of(null)),
);
@if (form.controls.coupon.touched
&& form.controls.coupon.hasError('badCoupon')) {
<p class="error">This coupon does not work.</p>
}
<button (click)="pay()"
[disabled]="form.pending || saving()">Pay</button>
- With timer, a new key press cancels the timer before the request is sent. Only the last value is checked.
- Show the error after touched. Use markAllAsTouched in pay() so errors appear if the user presses Pay early.
- Disable the button while pending and while saving.
Follow-up question: The email field must be checked for “already has an account” and also must match an “email again” field. Where do you put each validator?
Follow-up answer:
- “Already has an account” is an async validator on the email control, with updateOn: ‘blur’ so it runs once when the user leaves the field.
- “Must match” is a sync validator on the group that holds both fields, so it runs when either field changes.
Red flag: Says client validation is enough and the server does not need to check the coupon again, or shows errors only from form.invalid.
14. An admin guard that still downloads the admin code
Question: This protects the admin area of our shop:
export const adminGuard: CanActivateFn = () => {
const auth = inject(Auth);
if (!auth.isAdmin()) {
inject(Router).navigate(['/login']);
return false;
}
return true;
};
export const routes: Routes = [
{
path: 'admin',
canActivate: [adminGuard],
loadChildren: () =>
import('./admin/admin.routes').then((m) => m.ADMIN_ROUTES),
},
];
What do you think? Is there a problem?
Short answer: Three problems. First, canActivate runs after the router has matched the route, and for loadChildren the matching downloads the lazy child routes. So every customer who opens /admin downloads the whole admin code, and can read it. Use canMatch to skip the route, so the code is never downloaded. Second, the guard calls router.navigate and returns false. That starts a second navigation while the first is being cancelled. Return a UrlTree instead, for example createUrlTree([‘/login’]). Third, the guard is only for the user experience. The admin API must check the role on the server for every call.
Hint (if the candidate says there is no problem): In the network tab, a normal customer who types /admin sees admin-routes.js (380 KB) downloaded, then a redirect to /login.
Why does this happen? (step by step)
- Navigation steps: match, guards, resolve, activate.
- To match /admin/orders, the router must know the child routes of admin, so it runs loadChildren during the match step.
- canActivate runs only in the guard step, after the download.
- navigate inside a guard starts a new navigation. The router must cancel the current one, and the order of events can get confusing, for example with other guards or with returnUrl.
The fix:
export const adminMatch: CanMatchFn = (route, segments) => {
if (inject(Auth).isAdmin()) return true;
return inject(Router).createUrlTree(['/login'], {
queryParams: { returnUrl: '/' + segments.join('/') },
});
};
{ path: 'admin', canMatch: [adminMatch],
loadChildren: () => import('./admin/admin.routes')
.then((m) => m.ADMIN_ROUTES) }
- canMatch runs in the match step, before loadChildren. If it says no, the code is not downloaded.
- A returned UrlTree is a clean redirect inside the same navigation.
- If you want the URL to look like it does not exist, return false: the router tries the next route, for example the 404 page.
- On the server, every /api/admin endpoint checks the role.
Follow-up question: The admin’s session can expire while the admin page is open. The guard already ran. What happens, and what do you do?
Follow-up answer:
- Guards run only on navigation. A page that is already open stays open.
- The next API call returns 401. An HTTP interceptor catches it and navigates to the login page with a returnUrl.
- For child pages, a canActivateChild guard runs again on every move inside the admin area.
Red flag: Thinks hiding the admin route is enough security, or thinks canActivate stops the lazy code from downloading in every case.
15. SSR and the saved currency
Question: We turned on SSR with hydration for the product page. This component shows the price:
@Component({
selector: 'app-price',
template: `
<p>{{ price() | currency: currency }}</p>
<small>Updated {{ now | date: 'shortTime' }}</small>
`,
})
export class Price {
readonly price = input.required<number>();
currency = localStorage.getItem('currency') ?? 'EUR';
now = new Date();
}
After the release, the server logs show errors and some users see the price change after a moment. What do you think? What is wrong?
Short answer: On the server there is no localStorage, so the constructor throws “localStorage is not defined” and the page fails or falls back to client rendering. Even when it works, the server and the browser render different things: the server does not know the saved currency, and new Date() gives a different time on each side, maybe in a different time zone. That is a hydration mismatch: the price and the time jump after hydration. Fix: keep the currency where the server can read it (a cookie, read from the request on the server), or read localStorage in afterNextRender and accept a short change. Make the time on the server once and pass it (or show it only in the browser).
Hint (if the candidate says there is no problem): The server log says “ReferenceError: localStorage is not defined”. In development, the browser console shows a hydration warning for app-price.
Why does this happen? (step by step)
- SSR runs the component code in Node.js. Browser globals like window, document and localStorage do not exist there.
- Field initializers run in the constructor, during render, so the error happens while the page is built.
- Hydration expects the browser’s first render to build the same DOM as the server.
- The browser reads USD from localStorage, the server used EUR. new Date() differs by seconds and by time zone. The texts differ, so Angular reports a mismatch.
The fix:
export class Price {
readonly price = input.required<number>();
private prefs = inject(Preferences); // reads the cookie
readonly currency = this.prefs.currency; // a signal
readonly updatedAt = input.required<Date>(); // from server data
}
- A Preferences service reads the currency cookie: on the server from the REQUEST token, in the browser from document.cookie. Both sides render the same currency.
- The update time comes from the product data that the server already loaded. The HTTP transfer cache gives the browser the same data, so no mismatch.
- If the value really exists only in the browser, set it in afterNextRender. The first render matches the server, then the value changes once.
- Format dates with a fixed time zone, or show relative time only after hydration.
Follow-up question: The page also has a third-party chat widget that changes the DOM itself. What do you do with it?
Follow-up answer:
- Load and start it in afterNextRender, so it never runs on the server.
- Put it in a container element that Angular does not render children into, or add ngSkipHydration to its host component.
- Better: load it with @defer (on idle), so it is not in the main bundle at all.
Red flag: Wraps everything in isPlatformBrowser so the server renders an empty page, or says hydration warnings can be ignored.
16. A price filter that does not update
Question: This is the product list with a price slider:
@Component({
selector: 'app-product-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<input type="range" min="0" max="500"
(input)="setMax($event)" />
@for (p of visible(); track p.id) {
<app-product-card [product]="p" />
}
`,
})
export class ProductList {
readonly products = input.required<Product[]>();
maxPrice = 500;
readonly visible = computed(() =>
this.products().filter((p) => p.price <= this.maxPrice),
);
setMax(e: Event) {
this.maxPrice = Number((e.target as HTMLInputElement).value);
}
}
When the user moves the slider, the list does not change. When new products arrive, the filter suddenly works. What do you think? Why?
Short answer: computed only tracks signals that it reads. maxPrice is a plain field, so it is not a dependency. The only dependency is products. Moving the slider changes the field, but nothing marks visible as dirty, so it returns its memoized, old result, even though the template is checked again after the input event. When new products arrive, products changes, visible runs again and reads the current maxPrice, so the filter “suddenly” works. Make maxPrice a signal and call maxPrice.set(…) in the handler.
Hint (if the candidate says there is no problem): Put a console.log inside the computed. It logs once at start, and again only when the products input changes, never when the slider moves.
Why does this happen? (step by step)
- While the computed runs, Angular records each signal read: here only products.
- A computed is memoized. When it is read again, it first checks if any dependency has a new version. If not, it returns the cached value without running.
- The input event marks the OnPush component for check, so the template reads visible() again. But products has no new version, so the cache is used.
- The plain field change is invisible to the signal graph.
The fix:
readonly maxPrice = signal(500);
readonly visible = computed(() => {
const max = this.maxPrice();
return this.products().filter((p) => p.price <= max);
});
setMax(e: Event) {
this.maxPrice.set(Number((e.target as HTMLInputElement).value));
}
- Now both signals are dependencies. Moving the slider pushes “dirty” to visible.
- The template is a consumer of visible, so the component is refreshed, also in a zoneless app.
- Reading maxPrice once before the filter is cleaner, and it is read in every run, so it stays a dependency.
Follow-up question: A teammate writes an effect that loads prices for the selected currency: first await this.api.rates(), then read this.currency() and this.cart(). It runs once and then never again. Why?
Follow-up answer:
- Dependencies are only tracked while the function runs synchronously. Everything read after the first await is not tracked.
- So the effect has no dependencies and never runs again.
- Read currency() and cart() first, at the top, then start the async work. Or use resource, whose params function is tracked and whose loader is async.
Red flag: Says to call ChangeDetectorRef.detectChanges or to remove OnPush. That does not help, because the computed itself is not dirty.