Sub topic 9
Templates, Interpolation and Binding
A component's template is the HTML that Angular renders for that component. Angular compiles it ahead of time into JavaScript instructions that create DOM nodes and update them when your data changes. This chapter covers the syntax that connects the template to the component class: interpolation, property binding, attribute, class and style binding, event binding, template reference variables and two-way binding with ngModel.
This chapter assumes you can create a standalone component (previous chapter), read basic TypeScript, and know the difference between an HTML element and its DOM object. Conditionals and loops (@if, @for), signals, and inputs and outputs each get their own later chapter. They appear here only in passing.
The Mental Model: Data Flows in Directions
Every binding has a direction. Data either flows from the class into the DOM, from the DOM back into the class, or both ways. The bracket style tells you which direction a binding goes.
| Syntax | Name | Direction | Example |
|---|---|---|---|
| `{{ expr }}` | Interpolation | Class to DOM (text) | `<h2>{{ title }}</h2>` |
| `[prop]="expr"` | Property binding | Class to DOM | `<img [src]="url" />` |
| `[attr.name]="expr"` | Attribute binding | Class to DOM | `<td [attr.colspan]="span">` |
| `[class.name]="bool"` | Class binding | Class to DOM | `<li [class.done]="isDone">` |
| `[style.prop]="expr"` | Style binding | Class to DOM | `<div [style.width.px]="w">` |
| `(event)="stmt"` | Event binding | DOM to class | `<button (click)="save()">` |
| `[(ngModel)]="field"` | Two-way binding | Both | `<input [(ngModel)]="name" />` |
A Complete Example
The component below uses each binding form. You can generate it with ng generate component profile-card and replace the contents of the generated TypeScript file, or keep it as a single file with an inline template.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
interface User {
name: string;
avatarUrl: string;
joined: number;
}
@Component({
selector: 'app-profile-card',
imports: [FormsModule],
template: `
<h2>{{ user.name }}</h2>
<p>Member since {{ user.joined }} ({{ currentYear - user.joined }} years)</p>
<img [src]="user.avatarUrl" [alt]="'Avatar of ' + user.name" width="96" />
<button
[disabled]="!canEdit"
[attr.aria-pressed]="editing"
[class.active]="editing"
[style.font-weight]="editing ? 'bold' : 'normal'"
(click)="toggleEdit()">
{{ editing ? 'Done' : 'Edit' }}
</button>
<label>
Name:
<input [(ngModel)]="user.name" [readonly]="!editing" />
</label>
<input #tag placeholder="Add a tag, press Enter" (keyup.enter)="addTag(tag.value); tag.value = ''" />
<p>Tags: {{ tags.join(', ') || 'none' }}</p>
<p (mousemove)="onMove($event)">Pointer x: {{ pointerX }}</p>
`,
styles: `.active { outline: 2px solid steelblue; }`,
})
export class ProfileCard {
user: User = {
name: 'Ada Lovelace',
avatarUrl: 'https://picsum.photos/96',
joined: 2019,
};
currentYear = new Date().getFullYear();
canEdit = true;
editing = false;
tags: string[] = [];
pointerX = 0;
toggleEdit(): void {
this.editing = !this.editing;
}
addTag(value: string): void {
const trimmed = value.trim();
if (trimmed) {
this.tags = [...this.tags, trimmed];
}
}
onMove(event: MouseEvent): void {
this.pointerX = event.offsetX;
}
}Use it from the root template with <app-profile-card /> and add ProfileCard to the root component's imports array.
Interpolation
Interpolation, written {{ expression }}, evaluates a template expression and writes the result into the DOM as text. Angular converts the result to a string. null and undefined render as an empty string.
Interpolation always sets text content and never parses HTML. If user.name contains <b>hi</b>, the user sees those characters literally. That escaping is what protects you against script injection through interpolation.
Template expressions look like JavaScript but are limited on purpose:
- They can read component fields and call component methods.
- They can't reference globals such as
window,document,consoleorMath. If you need one, expose it as a field, for examplecurrentYearin the example above. - They can't contain assignments (
=,+=),new, or increment operators. Event bindings are the exception, covered below. - They support optional chaining (
user?.address?.city), the nullish operator (??), ternaries and pipes ({{ price | currency }}).
Property Binding
Property binding, written [property]="expression", sets a DOM property on an element, a directive or a child component. The property is a field on the JavaScript object. It is not the HTML attribute.
The two often share a name but behave differently. The value attribute of an <input> is its initial value. The value property is what the user has currently typed. Angular binds to properties because properties hold live state and can take any type, not only strings.
The brackets change how Angular reads the right-hand side:
<button disabled="false">Still disabled</button>
<button [disabled]="false">Enabled</button>
<img src="user.avatarUrl" />
<img [src]="user.avatarUrl" />Without brackets, Angular treats the value as a plain string. disabled="false" sets the attribute, and the presence of any disabled attribute disables the button. src="user.avatarUrl" requests a file literally named user.avatarUrl. With brackets, Angular evaluates the expression.
Interpolation inside an attribute, such as <img src="{{ url }}">, is shorthand for a property binding that produces a string. It works when you want a string. Use brackets for booleans, numbers and objects.
Attribute, Class and Style Bindings
Some HTML attributes have no matching DOM property. ARIA attributes, colspan on table cells in some contexts, and custom data-* attributes are common examples. For these, use attribute binding with the attr. prefix: [attr.aria-pressed]="editing". If the expression evaluates to null or undefined, Angular removes the attribute.
Class bindings come in two forms:
[class.active]="editing"adds or removes one class based on a boolean.[class]="{ active: editing, compact: isSmall }"sets several at once. It also accepts a space-separated string or an array of class names.
Style bindings work the same way. You can attach a unit suffix: [style.width.px]="width" sets width: 120px when width is 120. [style]="{ color: c, 'font-size': size }" sets several properties at once.
Angular merges these bindings with static class and style attributes on the same element. It does not replace them, so class="card" [class.active]="x" keeps card.
Event Binding
Event binding, written (event)="statement", listens for a DOM event or a component output and runs a template statement when it fires. Template statements, unlike template expressions, may assign values and chain several actions with ;. The example uses this in addTag(tag.value); tag.value = ''.
Inside the statement, $event holds the event payload. For DOM events it is the native event object, so type the handler parameter to match (MouseEvent, KeyboardEvent, or Event). For input events you usually need a cast:
onInput(event: Event): void {
const value = (event.target as HTMLInputElement).value;
console.log(value);
}Angular also supports key event filters. (keyup.enter), (keydown.escape) and (keydown.shift.tab) fire only for those keys, so you don't have to check event.key yourself.
Template Reference Variables
A template reference variable, declared with #name on an element, gives the rest of the template a handle to that element. On a plain element it refers to the DOM node, so #tag on an <input> lets you read tag.value without adding a field to the class. On a component it refers to the component instance. The variable is visible throughout the template where it is declared, but not inside the class.
Two-Way Binding with ngModel
Two-way binding combines a property binding and an event binding. The syntax [(ngModel)]="user.name" is nicknamed "banana in a box" because the parentheses sit inside the brackets. Angular expands it to:
<input [ngModel]="user.name" (ngModelChange)="user.name = $event" />ngModel is a directive from FormsModule, so the component must list FormsModule in its imports array. You can write custom two-way bindings for your own components, a technique shown in the chapter on passing data between components.
Common Errors and How to Read Them
| Symptom | Cause | Fix |
|---|---|---|
| `NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'` | The directive providing the property is not imported | Add `FormsModule` (or the relevant component) to `imports` |
| Same error for `aria-label` or `colspan` | No DOM property with that name | Use `[attr.aria-label]` |
| `Property 'x' does not exist on type 'Y'` in a template | Typo or private member; strict template type checking is on | Fix the name; make the member `protected` or `public` |
| `Cannot read properties of undefined` at runtime | Reading a nested field before data arrives | Use `?.` or guard with `@if` |
| Button disabled despite `disabled="false"` | Missing brackets, so the string attribute was set | Write `[disabled]="false"` |
| `NG0100: ExpressionChangedAfterItHasBeenCheckedError` (dev mode) | An expression returns a different value on a second check, often from a side effect | Remove side effects from expressions |
New projects enable strictTemplates in tsconfig.json. With it on, the compiler type-checks every binding, so a string bound to a number input is a build error instead of a runtime bug. Keep it enabled.
Exercise
In the example component, why does [attr.aria-pressed]="editing" use the attr. prefix while [disabled]="!canEdit" does not?
Show answer
disabled is a real DOM property on HTMLButtonElement, so property binding sets it directly. aria-pressed exists only as an HTML attribute with no matching DOM property in Angular's schema, so binding [aria-pressed] raises a "Can't bind" error. The attr. prefix tells Angular to call setAttribute instead.
Exercise
A teammate writes <p>Total: {{ items.reduce((s, i) => s + i.price, 0) }}</p> and later <p>Today: {{ new Date().toDateString() }}</p>. Which of these compile, and what would you change?
Show answer
Neither compiles. Template expressions don't support arrow functions or new. Move the logic into the class: add a total() method or, better, a computed signal for the sum, and a today = new Date().toDateString() field. Then interpolate {{ total() }} and {{ today }}.
Exercise
Rewrite <input [(ngModel)]="query" /> as separate one-way bindings, and say what must be imported for either version to compile.
Show answer
<input [ngModel]="query" (ngModelChange)="query = $event" />. Both versions need FormsModule in the component's imports array, because ngModel and ngModelChange come from the NgModel directive.