Sub topic 5
The Default strategy and its cost
This chapter assumes you know how the change detection cycle walks the component tree and compares template bindings. It also assumes you can read basic Angular components with @for, input() and signals. Here you will see what the Default strategy does, why it is correct but expensive, and which template habits make that cost worse.
What the Default strategy does
Every Angular component uses the Default strategy unless you say otherwise. In the API it is ChangeDetectionStrategy.Default, and its rule is simple: the component is checked on every change detection cycle, whatever caused the cycle.
A check means Angular re-evaluates each binding in the component's template. It compares the new value with the one stored from the previous cycle. If a value differs, Angular updates the DOM node. Then it moves on to the child components and repeats the process.
You rarely need to write the strategy out, but doing so shows what the default is:
import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
selector: 'app-greeting',
changeDetection: ChangeDetectionStrategy.Default,
template: `<p>Hello, {{ name }}</p>`,
})
export class Greeting {
name = 'Ada';
}Default is the safe choice. Angular makes no assumption about how your data changes. You can mutate an object, assign a field in a timer callback, or change a value in a promise handler. After the callback finishes, Zone.js notifies Angular, Angular runs a cycle, and the view catches up. You do not need to tell Angular which component changed.
Where the cost comes from
The Default strategy trades work for convenience. Angular cannot know which component's data changed, so it checks all of them, from the root down.
Only Item 2 could have changed. The other six components are checked anyway. In a small app this takes microseconds. In an app with thousands of components, such as a big table or dashboard, it can take long enough to drop frames.
The work in one cycle has three parts:
- Visiting components. Angular walks every view in the tree.
- Evaluating bindings. Each interpolation, property binding and similar expression runs again.
- Comparing values. Each result is compared with the stored previous value.
The first and third parts are cheap per binding. The second part is where cost can grow without limit, because a binding can call any code you write.
Triggers are broad
Zone.js patches browser APIs such as setTimeout, addEventListener and Promise. When a patched callback finishes inside the Angular zone, Angular schedules a cycle. This includes events that your templates never use:
- A
mousemovelistener that does nothing visible. - A
setIntervalpolling a server every 500 ms. - A WebSocket message that only updates a non-displayed value.
- A resolved promise from a library.
Each one starts a full pass over the tree. With the Default strategy, the cost of the app is roughly cycles per second × bindings in the tree × cost per binding. Reducing any of the three factors helps. Later chapters cover reducing the number of cycles and the number of components checked. This chapter focuses on the third factor.
Template expressions run on every cycle
Because Angular re-evaluates each binding on every cycle, any function called from a template runs on every cycle. Angular does not memoize it. Here is a component that shows the effect:
import { Component } from '@angular/core';
interface Item {
id: number;
name: string;
price: number;
}
@Component({
selector: 'app-price-list',
template: `
<button (click)="noop()">Click me</button>
<ul>
@for (item of items; track item.id) {
<li>{{ item.name }}: {{ formatPrice(item.price) }}</li>
}
</ul>
`,
})
export class PriceList {
items: Item[] = [
{ id: 1, name: 'Pen', price: 1.5 },
{ id: 2, name: 'Notebook', price: 4 },
{ id: 3, name: 'Bag', price: 25 },
];
formatPrice(price: number): string {
console.log('formatPrice called');
return '$' + price.toFixed(2);
}
noop() {}
}Open the console and click the button. The handler does nothing, yet formatPrice called appears three times, once per item. Each further event, such as a click anywhere on the page or a timer, logs three more lines.
In development mode you will usually see six lines per cycle instead of three. Angular runs a second verification pass that evaluates every binding again. It does this to detect values that changed during the first pass, which is the source of the ExpressionChangedAfterItHasBeenChecked error covered in a later chapter. The second pass does not happen in production builds.
Which expressions are cheap
Not every binding has the same cost. The table shows what happens to each kind on every cycle.
| Binding source | Work per cycle | Notes | Column |
|---|---|---|---|
| Plain field, `{{ name }}` | One property read and one comparison | Cheapest option. | |
| Method call, `{{ format(x) }}` | The method runs every time | Cost is whatever the method does. | |
| Getter, `{{ total }}` | The getter body runs every time | Looks like a field but behaves like a method. | |
| Pure pipe, `{{ x \ | currency }}` | Re-runs only if the input reference changes | Angular caches the last result. |
| Impure pipe | Runs every cycle | Needed for stateful pipes, but costly. | |
| Signal read, `{{ count() }}` | A cheap read | A `computed` signal caches its result until its dependencies change. |
The problem is rarely a single call. It is the multiplication: a method that sorts a 2,000-element array, called in a template inside a loop of 100 rows, can run 100 sorts on every mouse movement.
Moving the work out of the template
The usual fix is to compute the value once, when its inputs change, and bind to the stored result. With signals, computed does this:
import { Component, computed, signal } from '@angular/core';
interface Item {
id: number;
name: string;
price: number;
}
@Component({
selector: 'app-price-list',
template: `
<ul>
@for (row of rows(); track row.id) {
<li>{{ row.name }}: {{ row.label }}</li>
}
</ul>
`,
})
export class PriceList {
items = signal<Item[]>([
{ id: 1, name: 'Pen', price: 1.5 },
{ id: 2, name: 'Notebook', price: 4 },
{ id: 3, name: 'Bag', price: 25 },
]);
rows = computed(() =>
this.items().map((item) => ({
...item,
label: '$' + item.price.toFixed(2),
})),
);
}The computed callback runs once at first read. After that it runs only when items is set to a new value. Cycles that don't change items just read the stored array. A pure pipe gives a similar result when your data is not in signals. Use a pipe when the transformation belongs to the display, and computed when it belongs to the component's state.
Two other habits help with the Default strategy:
- Keep
ngDoCheckbodies andngAfterViewCheckedhooks small. They run on every cycle for every component that defines them. - Always give
@foratrackexpression that uses a stable identity, such asitem.id. Without it, Angular may recreate DOM nodes when the array is replaced.
Edge cases
- Mutation is always visible. Under Default,
this.user.name = 'Grace'shows up on the next cycle, because Angular re-readsuser.name. This is the main behavior that changes under OnPush, which is the next topic. - Every cycle starts at the root. A click inside a deeply nested component still checks its siblings and ancestors. Angular cannot start a pass from the middle of the tree under Default.
- Mixed trees. A Default component placed inside an OnPush parent is only checked when the parent is checked. The Default setting means "check me whenever my parent is checked", not "check me on every cycle regardless". Chapters on OnPush explain this further.
- Side effects in bindings. A method that changes state, such as incrementing a counter that is also displayed, makes the view unstable between passes. This is a common source of
ExpressionChangedAfterItHasBeenChecked. Keep bound expressions free of side effects.
Counting checks yourself
You do not need a profiler to see the problem. A console.log in a suspect method, as in the first example, tells you how often it runs. Compare the count in one cycle with the number of rows on screen and with how often cycles occur. If a handler that does nothing visible produces many log lines, the cost is coming from the Default strategy plus an expensive binding.
Exercise
A template contains {{ expensiveSum() }} inside an @for loop of 50 rows. The user moves the mouse over the page, and a mousemove listener inside the Angular zone does nothing visible. How many times does expensiveSum run per mouse event in a production build with the Default strategy, and why?
Show answer
50 times per event. Zone.js triggers a change detection cycle after the listener runs. Under Default, every component is checked and every binding is re-evaluated. Angular does not cache the method result, so each of the 50 rows calls expensiveSum again. In development mode the verification pass would make it about 100.
Exercise
You have a getter get visible() { return this.items.filter(i => i.active); } bound in a template. Name one way to stop it from filtering on every cycle, and say what triggers recalculation in your solution.
Show answer
Make items a signal and replace the getter with visible = computed(() => this.items().filter(i => i.active)). The filter then runs only when items is set to a new value. A pure pipe that filters its input would also work, and it recalculates only when the input array reference changes.