Sub topic 14
Finding unnecessary checks with Angular DevTools
This chapter assumes you know the Default and OnPush strategies, how markForCheck works, how signals mark a component for checking, and how Zone.js triggers a cycle. It shows how to measure change detection in a running app, so your tuning is based on evidence.
Why measure first
Change detection is cheap per binding. Trouble comes from multiplication: thousands of bindings, checked on every browser event, some of them calling slow code. You can't spot this by reading templates, because the cost depends on how often cycles run and which components each cycle reaches.
Angular DevTools is a browser extension for Chrome and Firefox. It adds an "Angular" tab to the browser developer tools. It has two parts that matter here:
- The Components tab shows the component tree and the state of each component.
- The Profiler tab records change detection cycles and reports how long each one took and where the time went.
DevTools only works with applications built in development mode. A production build strips the hooks it needs, so the extension reports that the page is not an Angular app or is not in development mode. Development builds are also slower than production builds, so use the numbers to compare components and runs. Don't treat them as production timings.
Menu names and layout change between DevTools releases. The ideas below stay the same, but a button may be labeled differently in your version.
Step 1: Inspect the tree in the Components tab
Open the Components tab before profiling. It shows the same tree Angular walks during a cycle. Two things are useful:
- Components using
OnPushcarry a small marker next to their name in the tree. A large subtree with no markers is a candidate for the strategy, because every component in it is checked on every cycle. - Selecting a component shows its inputs, outputs and properties. You can confirm what a component holds and whether a parent passes it a new reference or the same one.
This tab doesn't prove that a component is checked too often. It tells you where to look when you read the profile.
Step 2: Record a profile
In the Profiler tab, press the record button, perform the interaction you suspect (type in a field, scroll, move the mouse, wait for a timer), then stop recording.
The result is a bar chart. Each bar is one change detection cycle, in time order. Two properties of a bar carry the information:
- Height and color show how long the cycle took. Taller, warmer bars are slower.
- The number of bars shows how often cycles ran.
Read the chart before opening any bar. These patterns point to different causes:
| Pattern in the chart | Likely cause |
|---|---|
| Many short bars while you only moved the mouse | A `mousemove`, `scroll` or `pointermove` listener inside the zone starts a cycle for each event |
| Bars at a steady interval with no interaction | A `setInterval`, polling `setTimeout` or a repeating RxJS timer inside the zone |
| A few tall bars | Expensive template work, such as method calls that sort or filter in a binding |
| Many tall bars | Both problems at once: frequent cycles that each do too much |
Step 3: Open a bar and find the expensive components
Select a bar to see where that cycle spent its time. DevTools shows a flame graph of the component tree. Each block is a component, and its width is the time spent on it. The details panel lists how long the component's template function and its lifecycle hooks took.
Two readings are useful:
- Which components appear at all. A component that appears in a cycle triggered by an unrelated event was checked unnecessarily. An OnPush component whose inputs didn't change and that marked nothing dirty should not appear.
- Which blocks are wide. A wide block in a small component usually means slow work in its template or its hooks. A wide parent block made of many narrow children means there are a lot of components, and skipping the subtree would save time.
Keep the cause separate from the symptom. A component may appear because its parent is checked and the component is Default, even though nothing about the component changed. The fix then lives on that component, not on its parent.
A worked example
This component sorts 5000 rows with a method called from the template. It uses the Default strategy.
import { Component } from '@angular/core';
interface Row {
id: number;
label: string;
score: number;
}
@Component({
selector: 'app-report',
template: `
<ul>
@for (row of sortedRows(); track row.id) {
<li>{{ row.label }}: {{ row.score }}</li>
}
</ul>
`,
})
export class Report {
rows: Row[] = Array.from({ length: 5000 }, (_, i) => ({
id: i,
label: `Row ${i}`,
score: (i * 7919) % 1000,
}));
sortedRows(): Row[] {
return [...this.rows].sort((a, b) => a.score - b.score);
}
}Place it in an app that has a search box elsewhere on the page. Record while typing in the search box. Every keystroke starts a cycle, and in every cycle the profiler shows Report taking most of the time, even though the rows never changed. The method runs each cycle because Angular can't know that its result is the same as last time.
The fix has three parts. Hold the data in a signal, derive the sorted list with computed so it is recalculated only when the rows change, and switch the component to OnPush so it is skipped when nothing it depends on changes.
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
interface Row {
id: number;
label: string;
score: number;
}
@Component({
selector: 'app-report',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ul>
@for (row of sortedRows(); track row.id) {
<li>{{ row.label }}: {{ row.score }}</li>
}
</ul>
`,
})
export class Report {
rows = signal<Row[]>(
Array.from({ length: 5000 }, (_, i) => ({
id: i,
label: `Row ${i}`,
score: (i * 7919) % 1000,
})),
);
sortedRows = computed(() => [...this.rows()].sort((a, b) => a.score - b.score));
}Record the same interaction again. Report should no longer appear in the keystroke cycles, and the bars should be shorter. Compare the two recordings. If the bars didn't change, your hypothesis was wrong, and you should look elsewhere.
Counting checks without DevTools
DevTools shows cycles, but sometimes you want a plain number for one component, for example in an automated test or a remote debugging session. A function called from the template runs only when Angular evaluates that component's template, so it counts template checks directly.
import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
selector: 'app-probe',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Probe {{ trace() }}</p>`,
})
export class Probe {
trace(): string {
console.count('Probe template checked');
return '';
}
}Don't use ngDoCheck for this. Angular calls ngDoCheck on a child whenever its parent's view is checked, even if the child is OnPush and its own template is then skipped. It therefore counts parent checks, not checks of the component's own view. Remove the probe once you finish, since it is itself a method call in a template.
Common fixes and what to record afterwards
Match the pattern you found to a fix, then record again.
| Finding | Fix | What to check in the next recording |
|---|---|---|
| Many cycles from `mousemove` or `scroll` | Register the listener in `NgZone.runOutsideAngular` and re-enter with `NgZone.run` only when the view must change | Bar count drops while you move the mouse |
| Cycles at a fixed interval with no UI change | Start the timer outside the zone, or stop it when it is not needed | The regular bars disappear |
| An unrelated component appears in every cycle | Set OnPush and pass new references, or use signals | The component is absent from cycles it doesn't depend on |
| A wide block caused by a template method | Move the work into `computed`, a pure pipe or a precomputed field | The block narrows, and cycle time falls |
| A large subtree with no OnPush markers | Convert the root of the subtree to OnPush, then its children | The whole subtree is skipped in unrelated cycles |
After you convert a component to OnPush, test the interactions that used to work. A component that stopped updating after the change was relying on Default checking, and needs a new input reference, markForCheck, the async pipe or a signal.
Workflow summary
Change one thing per iteration. If you convert three components to OnPush and move a listener out of the zone at once, you can't tell which change helped, and you can't tell which one broke an update.
Gotchas
- Recording includes your own interaction. Move the mouse or type only in the part of the test you mean to measure, or the chart will mix unrelated cycles.
- Zoneless apps show cycles differently. Without Zone.js, cycles run only when a signal,
markForCheck, an event listener or a similar notification schedules one. Constant cycles then point to something scheduling them repeatedly, not to a stray timer. - A cycle may appear with little work in it. A short bar with few components is normal. The tree is walked from the root each time, and OnPush subtrees are skipped quickly. Only act on bars that are frequent or tall.
- Component names can be unclear in minified or heavily wrapped code. Profile a development build so the class names match your source.
Exercise
You record a profile while only moving the mouse over a page. DevTools shows 200 short bars, and the flame graph for each bar shows a Default-strategy dashboard component with 1,500 bindings. What would you change first, and how would you confirm the fix worked?
Show answer
Find the mousemove listener that runs inside the Angular zone, since it starts a cycle for every event. Register it in NgZone.runOutsideAngular and call NgZone.run only when the view needs updating. Then record the same mouse movement again. The number of bars should fall sharply, and the dashboard should disappear from the cycles that no longer happen. Converting the dashboard to OnPush is a second step, and you should do it separately so you can see its effect.
Exercise
Why is ngDoCheck a poor way to count how often an OnPush component's own template is evaluated?
Show answer
Angular calls ngDoCheck on a child each time its parent's view is checked, even when the child is OnPush and its template is then skipped. The count measures parent checks. A function called from the component's own template runs only when that template is evaluated, so it counts the checks you want.