Sub topic 1
How Angular learns that something may have changed
Prerequisites
This chapter assumes you can build Angular components with templates and data binding, and that you know how component inputs work. You should also know what an Observable is and how a subscription delivers values. Finally, you should be comfortable with the difference between two variables pointing at the same object and two separate copies of it.
The problem: the view must match the data
An Angular template shows values from your component class. When a field changes, the DOM must change too. Angular does this work in a step called change detection. During change detection, Angular walks the component tree, evaluates each template binding, and compares the result with the value it rendered last time. If a value differs, Angular updates the DOM.
That raises two questions. When should Angular run this step? And how does it find out that something may have changed? Your code just assigns this.count = 5. Nothing in plain JavaScript announces that assignment.
Zone.js watches asynchronous work
Angular's traditional answer is Zone.js, a library that patches the browser's asynchronous APIs. A zone is an execution context that survives across async calls. Zone.js wraps APIs such as these:
- DOM event listeners (
click,input,keydown) setTimeoutandsetIntervalPromisecallbacksXMLHttpRequestandfetch
Because the wrappers run before and after your callback, Zone.js knows when a piece of asynchronous work starts and finishes. Angular runs your application inside a zone called NgZone. When the zone reports that your callback has finished and no more microtasks are pending, NgZone emits an event. Angular listens to it and runs change detection over the whole application.
The consequence is that Angular does not know what changed. It only knows that something might have, because some async task just ran. So it checks everything.
A component that updates without any extra code
The following component changes a field inside a setTimeout. You never tell Angular to refresh the view, yet the new text appears.
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<p>{{ message }}</p>`,
})
export class GreetingComponent {
message = 'Loading...';
constructor() {
setTimeout(() => {
this.message = 'Hello from a timer';
}, 1000);
}
}The timer callback runs inside the Angular zone. When it returns, Zone.js notifies NgZone, Angular runs change detection, sees that message now differs from the rendered text, and updates the paragraph. This works because every component uses the default strategy unless you choose otherwise.
What the default strategy checks
With the default strategy, a change detection pass visits every component in the tree, starting at the root and moving down through each child. For each component, it re-evaluates all template bindings. The order is predictable: parent bindings first, then children.
This is simple and safe. A mutation anywhere is picked up, because everything is checked after every event. The cost is that the work grows with the size of the tree, and it happens on every event, including ones that cannot affect most components. Consider a mouse move handler or a timer that fires every 100 milliseconds in a tree of several hundred components. Each tick re-evaluates every binding in every component, even when only one small widget has new data.
The cost can be larger than it looks. Template expressions such as method calls or getters run on every pass, so an expensive function in a template runs again and again.
Seeing the cost for yourself
You can observe how often Angular re-evaluates a template by putting a logging getter in it. This is for experiments only.
import { Component } from '@angular/core';
@Component({
selector: 'app-probe',
template: `
<p>{{ checked }}</p>
<button (click)="noop()">Click me</button>
`,
})
export class ProbeComponent {
private runs = 0;
get checked(): string {
this.runs++;
console.log('ProbeComponent checked', this.runs);
return `Checks so far: ${this.runs}`;
}
noop() {
// Changes nothing, but the click still triggers change detection.
}
}Click the button in a development build and watch the console. The count rises even though no data changed. In development mode, Angular also runs an extra verification pass, so you may see two log lines per event.
Why this matters for OnPush
Default change detection trades efficiency for convenience. Zone.js tells Angular when to look, but not where. The next chapters introduce ChangeDetectionStrategy.OnPush, which lets a component say, "Skip me unless one of my own inputs or events gives you a reason to check me." Zone.js still triggers the pass, but OnPush subtrees are skipped when they have no reason to be checked.
Exercise
A component's template contains {{ expensive() }}, where expensive() is a method that loops over a large array. The page has a setInterval that fires every second and changes nothing visible. With default change detection, how often does expensive() run, and why?
Show answer
It runs at least once per second, and more often if other events occur. Zone.js patches setInterval, so after each callback NgZone signals that work finished and Angular runs change detection over the whole tree. Angular cannot tell that nothing changed, so it re-evaluates every binding, including the method call. In development mode it runs once more per pass for the verification check.
Exercise
What two pieces of information does Zone.js give Angular, and what does it not give?
Show answer
It tells Angular that an asynchronous task has started and finished, so Angular knows when to run change detection. It does not tell Angular which component or which value changed, so the default strategy has to check every component.