In the Angular CDK's *cdkVirtualFor, why does a row's checkbox state show up on a different audit entry after scrolling, and how do you fix it?
answer
- views outlive the rows they showed
- only the context is swapped
- a cache of twenty
- state belongs to the data
- trackBy is not the cure
basics
~20 s*cdkVirtualFor recycles detached row views through a template cache and swaps only their context item, so unbound DOM state and a child component's fields travel to whichever entry reuses the view. Keep row state keyed by entry id.
solid answer
~40 sWhen a row leaves the rendered range, `*cdkVirtualFor` detaches its view and keeps it in a template cache (20 views by default, `templateCacheSize` in the microsyntax). A row entering the range reuses a cached view: the directive swaps the item and the index variables, but the DOM and any child component instances are the same objects. An unbound `<input type="checkbox">` keeps its checked state, and a row component's internal `selected` signal keeps its value — now shown on another entry. Fix it by keeping per-row state in component state keyed by entry id, such as a signal holding a `Set` of flagged ids, and binding `[checked]` from it. `trackBy` and `templateCacheSize: 0` are not fixes: trackBy only matters when data is replaced, and no cache means the state is lost instead.
code
ts · 31 linesimport {Component, input, signal} from '@angular/core';
import {ScrollingModule} from '@angular/cdk/scrolling';
interface AuditLine { id: number; text: string; }
@Component({
selector: 'app-audit-review',
imports: [ScrollingModule],
template: `
<cdk-virtual-scroll-viewport itemSize="32" class="log">
<label class="line" *cdkVirtualFor="let line of lines(); trackBy: trackById">
<input type="checkbox" [checked]="flagged().has(line.id)" (change)="toggle(line.id)" />
{{ line.text }}
</label>
</cdk-virtual-scroll-viewport>
`,
styles: `.log { height: 480px; } .line { display: block; height: 32px; box-sizing: border-box; }`,
})
export class AuditReview {
readonly lines = input.required<AuditLine[]>();
readonly flagged = signal(new Set<number>());
readonly trackById = (_index: number, line: AuditLine) => line.id;
toggle(id: number) {
this.flagged.update(ids => {
const next = new Set(ids);
if (next.has(id)) next.delete(id); else next.add(id);
return next;
});
}
}go deeper
Recall that *cdkVirtualFor reuses row views as you scroll and that anything not bound to the data can appear on the wrong row.
Explain the cache mechanics: detach, cache up to 20, reuse with a new $implicit, and why bindings survive reuse while DOM and component fields do not.
Fix it properly by moving state into the data model keyed by id, and explain why trackBy and a zero cache are not fixes; then list the other things windowing breaks.
Set the team rule that row components in virtual lists are stateless projections, and weigh the template cache size against memory and fling performance with profiling data.
## How `*cdkVirtualFor` reuses views `*cdkVirtualFor` is the Angular CDK's repeater for `<cdk-virtual-scroll-viewport>`. As the user scrolls a 100,000-line audit log, rows constantly leave and enter the rendered range. Creating and destroying an embedded view — DOM nodes, bindings, child components — for every one of them would be wasteful, so the directive **recycles** views: 1. A row leaves the range: its view is **detached** from the DOM and, if the cache has room, stored in a **template cache**. 2. A row enters the range: the directive takes a cached view, sets its context's `$implicit` to the new item, updates `index`, `count`, `first`, `last`, `even` and `odd`, and inserts it. 3. Change detection then re-evaluates the template's **bindings** against the new item. Anything the template **binds** is therefore correct after reuse. Anything that lives **in the view rather than in a binding** is not reset. ## The symptom Two common cases carry state across entries: - **Unbound DOM state.** An `<input type="checkbox">` with no `[checked]` binding keeps the checked flag the browser stored on that element. Tick entry 12, scroll down, and the reused element appears ticked on entry 40. - **Child component state.** A row component `<app-audit-line [line]="line">` with an internal `selected = signal(false)` receives the new `line` input, but its own signal keeps the old value, because the component instance is reused, not recreated. The same applies to scroll position inside a row, an open native `<details>`, or text typed into an unbound input. None of these is a bug in the CDK: recycling is documented behaviour that exists for scrolling performance, and it is visible only when a template keeps state the data does not describe. A quick way to confirm the diagnosis is to set `templateCacheSize: 0` temporarily — if the wrong-row ticks disappear (and turn into lost ticks), recycling was the carrier. ## Fixes 1. **Lift row state into component state keyed by entry id.** Hold, for example, `flagged = signal(new Set<number>())` in the viewer component, bind `[checked]="flagged().has(line.id)"` and update the set on change. The reused view re-reads the binding and shows the right state. 2. **Make row components stateless about identity.** Derive `selected` from an input (`[selected]="flagged().has(line.id)"`) and emit an output on change instead of holding the flag inside. 3. **Reset what cannot be bound.** If a third-party row widget keeps internal state, reset it when its input changes, or key its state by the item's id. ## What `trackBy` does and does not do `*cdkVirtualFor` accepts `cdkVirtualForTrackBy` (`trackBy:` in the microsyntax). The function receives the item's index **in the full data source**, not in the rendered slice, plus the item, and returns its identity. - **It helps when data is replaced.** A polling refresh that returns 100,000 new objects for the same entries would otherwise look like every rendered item changed; with `trackBy: trackById` the views stay attached to their entries and only `$implicit` is updated. - **It does not stop scroll recycling.** Scrolling removes entries from the range and adds different ones; their identities differ whatever `trackBy` returns, so cached views are still handed to new entries. ## Tuning the template cache | Setting | Effect | |---|---| | default (20) | up to 20 detached views kept for reuse; cheap scrolling | | `templateCacheSize: 0` | caching disabled; views leaving the range are destroyed | | a larger number | fewer view creations on long flings, more memory held by detached views | Setting the cache to 0 does **not** fix misplaced state: the view that held entry 12's tick is destroyed, so when entry 12 scrolls back it renders unticked. The state is lost rather than misplaced, which is still a bug. Reduce the cache for memory reasons — the CDK guide suggests it when templates are memory-heavy — not for correctness. ## Other things windowing breaks in an audit viewer - **Find-in-page** cannot find lines that are not rendered; provide your own search over the data. - **Focus** inside a row that scrolls out of range leaves with the view, so keyboard users can lose their place. - **DOM queries and element references** to rows are valid only while those rows are rendered; hold ids, not elements. - **Context variables** such as `index` and `odd` are relative to the full data set, so zebra striping and line numbers stay stable while scrolling. The rule that covers all of these: in a virtual list, the **data model is the source of truth**, and a row view is a temporary projection of whichever entry it currently shows.
- Does a recycled row component run ngOnInit again for its new entry?No. Reuse reattaches the same view, so the component instance and its lifecycle continue; only its inputs change. Logic that ran once in `ngOnInit` for 'its' entry runs again only if it reacts to the input — with a signal input, through `computed()` or an effect that reads it.
- When would you raise the template cache size?When profiling shows view creation dominating fast flings through heavy rows — many bindings or child components per row. A larger cache keeps more detached views ready, trading memory for fewer creations. Lower it, or set 0, when each row holds a lot of memory and fling speed matters less.
- Adding trackBy stops recycled rows from showing another entry's state.
- Setting templateCacheSize to 0 is the correct fix for misplaced row state.
- A recycled row component is re-created, so its internal fields reset.
- The trackBy index is the position within the rendered rows.
- Raising maxBufferPx keeps rows in the DOM, so state can safely live in the view.
- Recycling only affects performance and never changes what the user sees.