Sub topic 1
The component tree and its views
Change detection runs over a tree. Before you can reason about when a component is checked, you need a clear picture of what that tree contains and how Angular stores it at runtime. This chapter covers the component tree, the views Angular builds for it, and the direction in which checks travel.
Prerequisites
This chapter assumes you already know the following:
- How to write a standalone Angular component with a decorator, a selector and a template.
- Template binding syntax: interpolation, property bindings and event bindings.
- How component inputs and outputs pass data between a parent and a child.
- Basic TypeScript classes and decorators.
You do not need to know Zone.js, OnPush or signals yet. Later chapters introduce them, and they all build on the model described here.
From templates to a tree of components
An Angular application starts from one root component. That component's template uses other components, and those components use others. The result is a tree.
import { Component } from '@angular/core';
@Component({
selector: 'app-item',
template: `<li>{{ label }}</li>`,
})
export class Item {
label = 'Item';
}
@Component({
selector: 'app-list',
imports: [Item],
template: `
<ul>
<app-item />
<app-item />
</ul>
`,
})
export class List {}
@Component({
selector: 'app-root',
imports: [List],
template: `
<h1>Shop</h1>
<app-list />
`,
})
export class App {}This code produces the following component tree. App is the root. It contains one List, and the List contains two Item instances.
Two points about this tree matter for change detection:
- The tree is made of component instances, not component classes.
Itemis one class, but it appears twice in the tree, and each instance is checked on its own. - The tree follows the templates. A component sits below the component whose template declares it. Where a class is defined in the source files has no effect on the tree.
Views: the runtime structure behind each component
At runtime Angular does not walk your component classes directly. For each component instance it creates a view. A view is the internal data structure that holds everything Angular needs to keep one template in sync with the DOM:
- The DOM nodes the template created.
- The current values of the template's bindings, such as the last value of
{{ label }}. - References to child views, directives and embedded views.
- Flags that record whether the view is attached, dirty or currently being checked.
A component's template is compiled ahead of time into instructions. The compiled code has two parts, a creation part and an update part. The creation part runs once, when the view is first built, and creates the DOM nodes. The update part runs each time the view is checked, and it re-evaluates the bindings and writes any changed value to the DOM.
This split explains what "checking a component" means. It is the update part of that component's view running. It is not a re-render of the whole template, and it does not rebuild DOM nodes. Angular only touches a DOM node when a binding value differs from the one it stored.
Host views and component views
Each component has two kinds of view associated with it:
| View | What it holds | Which template it comes from |
|---|---|---|
| Component view | The nodes in the component's own template | The component's `template` |
| Host view | The component's host element and its bindings, such as `@HostBinding` and `host` metadata | The parent template, where the component's selector appears |
The host element is the element that matches the selector, for example <app-item>. Bindings on that element belong to the parent's view, while the content inside it belongs to the child's component view. You can see this when a parent binds a property on a child:
<app-item [label]="name" />The parent's view evaluates name and compares it with the previous value. If it changed, Angular writes the new value to the child's input. The child's own bindings are evaluated later, when Angular checks the child's view.
Embedded views
Some views do not belong to a component. When a template uses structural blocks such as @if or @for, Angular creates embedded views from a template fragment. An @for block with five items creates five embedded views. Embedded views belong to the component whose template contains the block, and they are checked together with that component.
import { Component } from '@angular/core';
@Component({
selector: 'app-names',
template: `
@if (names.length > 0) {
<ul>
@for (name of names; track name) {
<li>{{ name }}</li>
}
</ul>
} @else {
<p>No names yet.</p>
}
`,
})
export class Names {
names = ['Ada', 'Grace', 'Alan'];
}Here Names has one component view. Inside it, the @if block creates one embedded view, and the @for block creates three more. Adding a name creates another embedded view. Removing one destroys a view. This is why track matters: it lets Angular reuse an existing view for an item instead of destroying and recreating it.
How a check moves through the tree
The tree gives the order in which Angular checks things. A check starts at the root and moves downward. For each view, Angular does these steps in order:
- Update the input bindings of child components and directives in this view.
- Run lifecycle hooks such as
ngOnChangesandngDoCheckfor those children. - Evaluate the remaining bindings in this view and update the DOM where values changed.
- Move down into each child component view and repeat.
The order of the first and third steps in a real template is interleaved by position, but the principle holds: a parent is always processed before its children. Data flows in one direction, from parents to children.
A check never goes upward on its own. A child cannot change a value that its parent has already been checked against during the same pass without causing trouble. A later chapter covers ExpressionChangedAfterItHasBeenChecked, which is the error Angular raises when this one-way rule is broken in development mode.
Which views a check reaches
Every component view has a flag that tells Angular whether to check it. In the default setup all component views are included, so a pass visits the whole tree from the root. Later chapters show how the OnPush strategy changes this by skipping a view, and everything below it, when nothing about that view could have changed.
This is the reason the tree shape matters. Skipping a view skips its entire subtree. A component near the root that is skipped saves much more work than a leaf component that is skipped. Planning where to place strategy choices starts with knowing the tree.
Inspecting the tree in a running app
You can look at the tree of a running application in development mode with the global debugging helpers that Angular exposes in the browser console:
import { Component, ElementRef, inject } from '@angular/core';
@Component({
selector: 'app-debug',
template: `<p>Open the console and type ng.getComponent($0)</p>`,
})
export class Debug {
private host = inject(ElementRef);
constructor() {
console.log('Host element of this component:', this.host.nativeElement);
}
}In the browser console, select an element in the Elements panel and run ng.getComponent($0) to get its component instance. ng.getOwningComponent($0) returns the component whose template contains the element. These helpers exist only in development builds.
The Angular DevTools browser extension shows the same tree visually. A later chapter uses it to find components that are checked more often than they need to be.
Common mistakes
- Treating a class as a node. The tree contains instances. Two
Itemcomponents have separate views and separate stored binding values. - Expecting a child to be checked before its parent. Checks move top-down. A parent's bindings and the child's inputs are updated before the child's own template is evaluated.
- Thinking a check rebuilds the DOM. A check runs the update part of the compiled template and writes only the values that changed.
- Forgetting embedded views. Blocks like
@ifand@forcreate views that are checked as part of their owning component. They are not separate components.
Summary of the model
- The application is a tree of component instances that mirrors the templates.
- Each instance has a view that stores its DOM nodes and last-known binding values.
- Blocks such as
@ifand@foradd embedded views under the component that owns them. - A check runs from the root downward and updates a view's bindings and DOM, parent before child.
- Skipping a view skips its whole subtree, which is the basis for the OnPush strategy.
Exercise
A template contains <app-item /> three times inside an @for block that renders three items, and the @for block sits in the List component. How many component instances and how many embedded views of the @for block does this create, and which component's check handles the embedded views?
Show answer
It creates three Item component instances, each with its own component view, and three embedded views for the @for block, one per rendered item. The embedded views belong to List, so they are checked as part of List's check, and each Item view is then checked as a child of its embedded view's position in List's template.
Exercise
In <app-item [label]="name" /> written in the List template, which component's view evaluates the expression name, and when is the Item template's own {{ label }} binding evaluated relative to it?
Show answer
The List view evaluates name, because the binding is written on the host element in List's template. Angular then writes the value to Item's label input. Item's own {{ label }} binding is evaluated afterwards, when the check moves down into Item's component view.