Sub topic 13
Rendering large lists efficiently
This chapter assumes you can record a trace in the Performance panel, read a flame chart, and recognize change detection in a trace. It also assumes you know Angular's built-in control flow (@if, @for) and basic component inputs.
Lists are a common source of slow Angular screens. A table of a few thousand rows can freeze the page when it first renders, when it refreshes from the server, or when you sort it. The fix depends on which of those three cases you are in, so you profile first.
What a slow list looks like in a trace
Record a trace while you trigger the slow action: load the page, click Refresh, or change the sort order. Look for these signs.
- A long task (a red-cornered block over 50 ms) on the main thread, with many repeated
Create,Update, orDestroycalls in the Angular framework frames beneath it. - Purple Recalculate Style and Layout blocks right after the scripting work. The browser has to measure every DOM node you created.
- A DOM node count in the Performance panel's memory counters that jumps up and down on every refresh. Turn on the Memory checkbox before recording to see it.
If the scripting is slow, the cost is in Angular's work. If the Layout and Paint blocks dominate, the cost is the size of the DOM itself, and no change-detection tweak will fix that.
How @for decides what to reuse
When the array bound to a loop changes, Angular compares the old and new items. For each new item it looks for an old item with the same tracking key. A match keeps the existing DOM nodes and updates their bindings. A miss creates new nodes, and any unmatched old nodes are destroyed.
The track expression is required in @for, so you always choose a key:
@for (row of rows; track row.id) {
<app-row [row]="row" />
}With a stable id, a refresh that returns the same rows reuses every app-row. If the data changes, only the bindings that depend on it update.
Comparing track expressions
| Expression | Behavior | Typical use |
|---|---|---|
| `track row.id` | Reuses nodes while the id stays the same, even if the object is new | Data from a server with unique ids |
| `track row` | Reuses nodes only for the same object reference | Immutable data you keep in memory |
| `track $index` | Reuses nodes by position | Static lists that never reorder |
track $index looks harmless, but it breaks down when a list is reordered or has items inserted at the front. Every position now holds different data, so every row updates. Child components that hold state, such as an open dropdown or an input's text, also keep that state at the wrong row.
A runnable comparison
The component below replaces the whole array with new objects on every click, which is what a refetch does. Because the ids stay the same, track row.id keeps the existing li elements.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
interface Row {
id: number;
name: string;
}
@Component({
selector: 'app-row-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button (click)="refresh()">Refresh</button>
<ul>
@for (row of rows(); track row.id) {
<li>{{ row.name }}</li>
}
</ul>
`,
})
export class RowListComponent {
rows = signal<Row[]>(this.build());
refresh() {
this.rows.set(this.build());
}
private build(): Row[] {
const stamp = Date.now();
return Array.from({ length: 5000 }, (_, i) => ({
id: i,
name: `Item ${i} at ${stamp}`,
}));
}
}To see the difference, change track row.id to track row. Every refresh now creates new objects, so no old object matches a new one. Angular destroys 5,000 rows and creates 5,000 more. In the trace, the scripting block grows and the DOM node counter spikes. Switch back and record again. The counter stays flat, and the task is shorter.
Legacy *ngFor and trackBy
Older code uses *ngFor with a trackBy function. It does the same job, but the key is optional, which is why it is so often missing. If you profile a codebase that still uses *ngFor, search for loops without trackBy first. By default *ngFor tracks by object identity, which is the slow case for refetched data.
When reuse is not enough: too many nodes
A good track expression removes needless re-creation. It does nothing about the first render or about layout cost, because 5,000 rows still means roughly 5,000 times the DOM nodes per row. If your trace shows long Layout blocks, reduce the nodes that exist at once.
There are two common approaches.
- Pagination or "load more" limits the list to a page at a time. It is simple and keeps the page accessible, and it fits when users do not need to scroll through everything.
- Virtual scrolling renders only the rows in or near the viewport. The Angular CDK provides it:
import { Component } from '@angular/core';
import { ScrollingModule } from '@angular/cdk/scrolling';
@Component({
selector: 'app-virtual-list',
imports: [ScrollingModule],
template: `
<cdk-virtual-scroll-viewport itemSize="40" style="height: 400px">
<div *cdkVirtualFor="let item of items" style="height: 40px">
{{ item }}
</div>
</cdk-virtual-scroll-viewport>
`,
})
export class VirtualListComponent {
items = Array.from({ length: 100000 }, (_, i) => `Item ${i}`);
}This renders a few dozen elements for 100,000 items. The trade-offs are real:
- The fixed
itemSizemust match the real row height. Rows of varying height cause scroll jumps unless you use a custom strategy. - Browser find-in-page cannot see rows that are not in the DOM.
- Keyboard and screen reader navigation need extra care, because rows appear and disappear as the user scrolls.
- Row components are created and destroyed as the user scrolls, so scrolling itself can show up as scripting in a trace. Keep the row template cheap.
Keeping row updates cheap
Reuse means Angular checks each existing row on every change detection pass. With 5,000 rows, even a trivial row template adds up. Two measures help.
- Put
ChangeDetectionStrategy.OnPushon the row component and pass data through inputs. Angular then skips rows whose inputs have not changed. - Keep method calls and heavy pipes out of the row template. A function call such as
{{ format(row) }}runs once per row per pass. Compute the value once, in acomputedsignal or when the data arrives.
Angular DevTools shows this clearly. In its profiler, a list parent that triggers a pass should show most rows as skipped or very short. If every row appears in every pass, check whether the row is using the default strategy.
Verify the change
List fixes are easy to overrate, because a refresh feels faster even when it is not. Use the same procedure each time.
- Record the slow action in a production-like build with the same CPU throttling, and record it at least three times.
- Note the long task duration, the scripting total, and the peak DOM node count.
- Apply one change, for example the
trackexpression. - Record the same action again and compare the same numbers.
If you wrap the refresh in performance.mark and performance.measure, the Timings track gives you a labeled duration to compare directly. Change one thing at a time. If you add track, OnPush, and virtual scrolling together, you cannot tell which one helped.
Exercise
A table of 2,000 orders is refetched every 10 seconds. The server returns new objects with the same orderId values. A trace of each refresh shows a 300 ms long task with many Create and Destroy calls, and the DOM node count drops and rises on each refresh. The template uses @for (o of orders; track o). What change should you try first, and what should you check in the next trace?
Show answer
Change the key to track o.orderId. Because the refetch produces new object references, tracking by object identity treats every row as new, so Angular destroys and recreates all 2,000 rows. Tracking by id lets Angular reuse the nodes. In the next trace, with the same throttling and build, check that the long task is shorter, the Create and Destroy calls are mostly gone, and the DOM node count stays flat across refreshes.