Sub topic 1
How Angular Templates Connect to Component State
An Angular component has two parts. One is a TypeScript class that holds state and behavior. The other is a template, which is HTML extended with Angular syntax. Data binding is the set of rules that connects them. Values flow from the class into the DOM, and events flow from the DOM back into the class.
This chapter explains the model that every later chapter builds on: what a template expression is, what it can see, what it is allowed to do, and which direction data moves in each binding form. The individual binding forms get their own chapters later.
Prerequisites
This chapter assumes you already know:
- HTML and DOM basics, including the difference between an element in markup and the live DOM node the browser creates from it.
- TypeScript classes, fields, methods and type annotations.
- How to create and run an Angular component with the Angular CLI (
ng new,ng serve,ng generate component). - JavaScript events such as
clickandinput, and what an event object is.
The examples use standalone components, which are the default in current Angular versions. If your project uses NgModules, the template syntax is identical. Only the way components are declared and imported differs.
The Template Is Compiled, Not Interpreted
Angular does not read your template as HTML at runtime. The Angular compiler turns each template into JavaScript instructions. Those instructions create DOM nodes once and then update only the parts that depend on component state.
When you write {{ title }}, the compiler generates code that reads title from the component instance and writes the result into a text node. When title changes, Angular runs the update code during change detection, and only that text node is touched.
This has two practical results:
- Template errors are often caught at build time. With strict template type checking (
strictTemplates: trueintsconfig.json, the default for new projects), a typo like{{ titel }}fails the build. - Bindings are not string substitution. A binding attaches to a specific DOM node, property, or event listener, so Angular can update it precisely.
Template Expressions and Template Statements
Angular syntax inside a template comes in two kinds of code. Treating them as the same thing causes many beginner errors.
A template expression produces a value. It appears inside {{ }} and on the right side of a property binding such as [disabled]="...". Angular evaluates it every time it checks the component.
A template statement responds to an event. It appears on the right side of an event binding such as (click)="...". Angular runs it only when the event fires.
import { Component } from '@angular/core';
@Component({
selector: 'app-cart-summary',
template: `
<p>Items: {{ items.length }}</p>
<p>Total: {{ total() }}</p>
<button [disabled]="items.length === 0" (click)="clear()">Clear cart</button>
`,
})
export class CartSummaryComponent {
items: { name: string; price: number }[] = [
{ name: 'Pen', price: 2 },
{ name: 'Notebook', price: 5 },
];
total(): number {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
clear(): void {
this.items = [];
}
}In this template, items.length, total() and items.length === 0 are expressions. clear() is a statement. Notice that the template never writes this.. Inside a template, the component instance is the implicit context.
| Code kind | Where it appears | When it runs | May change state? |
|---|---|---|---|
| Template expression | `{{ }}`, `[prop]="..."`, `[attr.x]="..."` | Every change detection pass | No, it should be side-effect free |
| Template statement | `(event)="..."` | Only when the event fires | Yes, that is its purpose |
What an Expression Can See
The expression context is the set of names a template expression can refer to. It has three layers. Angular checks them from the innermost to the outermost:
- Template-local names: template reference variables (
#box), loop variables from@for, aliases from@if (x; as y), and@letdeclarations. - In template statements only, the
$eventobject for the current event. - Members of the component instance: public and protected fields, getters, methods and signals.
If a local name matches a component member, the local name wins. That can hide bugs:
import { Component } from '@angular/core';
@Component({
selector: 'app-shadowing',
template: `
<p>Component name: {{ name }}</p>
@for (name of names; track name) {
<p>Loop name: {{ name }}</p>
}
`,
})
export class ShadowingComponent {
name = 'Team list';
names = ['Ada', 'Grace'];
}Inside the @for block, name is the loop variable, not the component field. The output shows "Team list" once, followed by "Ada" and "Grace". Give loop variables distinct names (member of members) so nobody has to work out which layer a name comes from.
Template expressions cannot reach JavaScript globals. window, document, console, Math, JSON and Date do not exist in the expression context. {{ Math.round(price) }} fails to compile because Math is not a component member. Expose what you need from the class:
import { Component } from '@angular/core';
@Component({
selector: 'app-price',
template: `<p>Rounded: {{ round(price) }}</p>`,
})
export class PriceComponent {
price = 19.6;
protected round(value: number): number {
return Math.round(value);
}
}What an Expression May Do
Template expressions look like JavaScript, but they are a restricted subset. The restrictions exist because Angular may evaluate an expression many times per second, and the template should describe the view, not run logic.
Supported features include property access, method calls, arithmetic, comparison and logical operators, the ternary operator, array and object literals, optional chaining (user?.address?.city), the non-null assertion (user!.name), and pipes ({{ date | date:'short' }}).
Not supported in expressions:
- Assignment of any kind (
=,+=and similar). - The
newoperator. - Increment and decrement (
++,--). - Bitwise
|and&. The|character means the pipe operator in templates. - Declaring functions or classes inline.
The exact list has grown over recent releases, as operators such as typeof were added. The guiding rule stays the same: if it changes state or needs more than a line, put it in a component method.
Template statements are a little more permissive. They allow simple assignment ((click)="open = true") and chaining with ;. Even so, a named method such as (click)="toggle()" is easier to read, test and debug than an inline assignment.
Expressions Must Be Quick and Side-Effect Free
Angular evaluates every expression in a component's template during each change detection pass. An expression must therefore follow three rules:
- No side effects. Reading a value must not change state. A getter that increments a counter or calls an API breaks the model.
- Quick to compute. An expensive method in
{{ }}runs on every check, which may happen on each keystroke or timer tick anywhere in the app. - Idempotent. Evaluating it twice in a row with no state change in between must give the same result.
The third rule causes a well-known error. In development mode, Angular runs a second check right after the first. If an expression returns a different value the second time, Angular throws ExpressionChangedAfterItHasBeenCheckedError. This example triggers it:
import { Component } from '@angular/core';
@Component({
selector: 'app-unstable',
template: `<p>Lucky number: {{ lucky }}</p>`,
})
export class UnstableComponent {
get lucky(): number {
return Math.random();
}
}The fix is to compute the value once and store it, for example lucky = Math.random();. A related pitfall is a getter that returns a new array or object on every call, such as get active() { return this.items.filter(i => i.active); }. A property binding to it receives a new reference each time. That can cause extra work in child components and, with some bindings, the same error. A stored field or a computed() signal (covered in a later chapter) avoids this.
One-Way and Two-Way Data Flow
Every binding form moves data in a fixed direction. Knowing the direction tells you which side owns the value.
| Syntax | Name | Direction | Example |
|---|---|---|---|
| `{{ expr }}` | Interpolation | Class to DOM | `<h2>{{ name }}</h2>` |
| `[prop]="expr"` | Property binding | Class to DOM | `<img [src]="avatarUrl">` |
| `[attr.x]`, `[class.x]`, `[style.x]` | Attribute, class, style binding | Class to DOM | `<td [attr.colspan]="span">` |
| `(event)="statement"` | Event binding | DOM to class | `<button (click)="save()">` |
| `[(prop)]="field"` | Two-way binding | Both directions | `<input [(ngModel)]="name">` |
One-way bindings keep the component class as the single source of truth. The DOM shows what the class holds, and the only way to change state is through an event that calls component code. This makes data flow easy to trace: to find out why a value changed, look at the event handlers.
Two-way binding is shorthand, not a separate mechanism. [(x)]="value" expands to a property binding [x]="value" plus an event binding (xChange)="value = $event". The data still moves one way at a time, and the syntax only saves typing. Later chapters show this expansion for ngModel and for your own components.
Bindings on a child component follow the same rules. A parent passes data down through a property binding on the child's input and listens for changes through an event binding on the child's output. In a well-structured Angular app, data goes down the component tree through inputs and events come up through outputs.
Square Brackets Change What the Right Side Means
The brackets decide whether the right-hand side is evaluated. People often get this wrong:
import { Component } from '@angular/core';
@Component({
selector: 'app-brackets',
template: `
<input value="initial">
<input [value]="initial">
<button disabled="false">Still disabled</button>
<button [disabled]="false">Enabled</button>
`,
})
export class BracketsComponent {
initial = 'from the class';
}Without brackets, the right side is a plain string, so the first input shows the text "initial". With brackets, it is an expression, so the second input shows "from the class". The first button is disabled because the HTML disabled attribute is present, and its value "false" is just a non-empty string. The second button binds the boolean false to the disabled DOM property, so it is enabled. The chapter on property binding explains the difference between attributes and properties in detail.
Exercise
A template contains {{ formatTotal() }} and <button (click)="count = count + 1">. Which one is a template expression and which is a template statement, and why is it acceptable for only one of them to change component state?
Show answer
formatTotal() inside interpolation is a template expression. Angular evaluates it on every change detection pass, so it must be side-effect free and return the same value when state has not changed. count = count + 1 in the event binding is a template statement. It runs only when the click event fires, so changing state there is its purpose.
Exercise
A developer writes <p>{{ Math.max(a, b) }}</p> and the build fails. Explain the cause and give a fix.
Show answer
Template expressions can only see template-local names and members of the component instance, not JavaScript globals such as Math. Add a method or field to the component, for example protected larger() { return Math.max(this.a, this.b); }, and use {{ larger() }}. You can also store the result in a field or a computed signal.
Exercise
A component has get items() { return this.all.filter(i => i.visible); } and the template binds [list]="items" on a child component. What problem can this cause, and how do you avoid it?
Show answer
Each evaluation returns a new array reference, so the value is not stable between checks. This can trigger ExpressionChangedAfterItHasBeenCheckedError in development mode and makes the child see a "new" input on every pass. Compute the filtered array once when all changes and store it in a field, or use a computed() signal so the reference changes only when the data changes.