Sub topic 1
The Component Tree and Its Views
Prerequisites
This chapter assumes basic Angular components, templates, TypeScript classes, inputs, outputs, and JavaScript callbacks such as promises and timers.
The component tree and its views
Angular applications form a tree. The root component contains child components, which can contain more children. Each component has a view, which is Angular’s internal representation of the component’s template and its bindings.
Angular does not inspect the entire browser DOM as one undifferentiated structure. It checks component views and embedded views, such as the view created by an @if block or an @for loop. A component’s view can contain elements, text, directives, and child component views.
@Component({
selector: 'app-dashboard',
template: `
<app-header />
<app-user-list [users]="users" />
`,
})
export class Dashboard {
users = [{ name: 'Ada' }, { name: 'Grace' }];
}The dashboard view contains the header view and the user-list view. This structure gives Angular a predictable path for checking the application.
What Angular compares: template bindings
A binding connects a template expression to component state. Examples include {{ title }}, [disabled]="isSaving", and (click)="save()".
During a check, Angular evaluates these expressions and compares their current values with values from the previous check. When a value differs, Angular updates the corresponding DOM property, text, attribute, or directive input.
Angular does not automatically react to every JavaScript assignment at the exact moment it happens. A change must be followed by a check. This distinction explains why changing state and starting change detection are separate concerns.
How Zone.js tells Angular something may have changed
In the traditional Angular setup, Zone.js patches many asynchronous browser APIs, including timers, events, and promises. When a patched callback finishes, Angular is notified that application state might have changed. Angular can then schedule a change-detection cycle.
Zone.js does not identify which property changed. It only reports that an asynchronous task completed. Angular still evaluates bindings to discover what changed.
The change detection cycle, top to bottom
Angular starts at the root view and checks downward through the component tree. It evaluates bindings in each view, updates changed values, and continues into child views. A parent’s updated input can therefore affect a child during the same cycle.
Exercise
Why can a changed component property remain invisible until a later event or scheduled check?
Show answer
Assigning the property changes JavaScript state, but Angular must run a change-detection cycle before it evaluates the binding and updates the DOM.