Video lecture
Watch on YouTube(opens in a new tab)Sub topic 3
Displaying Data with Interpolation and Template Expressions
Interpolation is the most common way to get data from a component class onto the page. This chapter covers the {{ }} syntax, what a template expression can and cannot contain, how values become text, and the mistakes that tend to cause bugs.
It assumes you know TypeScript classes and the parts of a component from the earlier chapters: the @Component decorator, the selector, the template, and the class. Signals have their own chapter next. Here they appear only as function calls.
The Interpolation Syntax
Interpolation puts a template expression between double curly braces. Angular evaluates the expression, converts the result to a string, and writes it into the DOM as text.
import { Component } from '@angular/core';
interface User {
name: string;
address?: { city: string };
}
@Component({
selector: 'app-profile',
template: `
<h2>Hello, {{ user.name }}!</h2>
<p>City: {{ user.address?.city ?? 'Unknown' }}</p>
<p>You have {{ items.length }} {{ items.length === 1 ? 'item' : 'items' }}.</p>
<p>Subtotal: {{ subtotal() }}</p>
<p>With tax: {{ roundToCents(subtotal() * taxRate) }}</p>
`
})
export class ProfileComponent {
user: User = { name: 'Ada' };
items = [{ price: 4.5 }, { price: 10 }];
protected taxRate = 1.2;
subtotal() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
roundToCents(value: number) {
return Math.round(value * 100) / 100;
}
}This renders "Hello, Ada!", "City: Unknown", "You have 2 items.", "Subtotal: 14.5", and "With tax: 17.4". You can mix static text and several interpolations in the same text node, as the third paragraph does.
The Expression Context
A template expression is evaluated against the component instance. user.name means this.user.name, and you never write this yourself. Angular resolves a name in this order:
- Template variables, such as a
#refreference or the loop variable of an@forblock. - Members of the component class.
So a template variable with the same name as a class property hides that property inside its scope. The cause of a value that "should" be there but isn't is often a name clash like this.
Template expressions cannot see JavaScript globals. window, document, console, Math, and JSON are all unavailable. If you need one, wrap it in a method (as roundToCents does) or expose it as a class field:
import { Component } from '@angular/core';
@Component({
selector: 'app-dice',
template: `<p>Largest: {{ math.max(a, b) }}</p>`
})
export class DiceComponent {
protected readonly math = Math;
a = 3;
b = 7;
}What an Expression May Contain
Template expressions use a subset of JavaScript syntax plus a few additions of Angular's own.
| Allowed | Example |
|---|---|
| Property access and method calls | `user.name`, `subtotal()` |
| Arithmetic, comparison, logical operators | `price * qty`, `a === b`, `x && y` |
| Ternary | `n === 1 ? 'item' : 'items'` |
| Optional chaining and nullish coalescing | `user.address?.city ?? 'n/a'` |
| Array and object literals | `[1, 2]`, `{ a: 1 }` |
| Untagged template literals (v19.2+) | `` `${first} ${last}` `` |
| `typeof` (v19+); `in`, `**`, `void` (v20+) | `typeof value === 'string'` |
| Non-null assertion | `user.address!.city` |
| Not allowed | Why | Column | Column |
|---|---|---|---|
| Assignment: `=`, `+=`, `++`, `--` | Expressions must not change state (event bindings are the exception) | ||
| `new`, `instanceof` | Not part of the grammar | ||
| Bitwise `\ | ` and `&` | `\ | ` is the pipe operator |
| Statements: `if`, `for`, declarations | Expressions only; control flow uses `@if` and `@for` | ||
| Globals like `window`, `Math` | Not in the expression context |
The | character is a pipe, which a later chapter covers. In a template, {{ a | b }} runs value a through a pipe named b. It is never a bitwise OR.
From Value to Text
The conversion rules have consequences you can see on the page:
nullandundefinedrender as nothing. The page shows no "undefined" text, and Angular raises no error.- Numbers and booleans become
"42"and"true". - Arrays are joined with commas:
[1, 2, 3]renders as1,2,3. - Plain objects render as
[object Object]. If you see that on the page, you interpolated an object where you meant one of its properties. For debugging, use thejsonpipe.
Interpolated values are inserted as text, never parsed as HTML. If comment contains <b>hi</b>, the user sees the literal tags. This is what protects interpolation against cross-site scripting (XSS), so don't look for ways around it.
Interpolation also works inside attribute values, as in <img alt="Photo of {{ user.name }}">. Angular turns that into a property binding, which the property binding chapter covers.
Strict Type Checking and Null Safety
With strictTemplates turned on (the default in new projects), the compiler type-checks your expressions. If user.address is typed as optional, then {{ user.address.city }} fails to compile with "Object is possibly 'undefined'". You have three fixes:
user.address?.citystops at undefined and renders nothing.user.address?.city ?? 'Unknown'supplies a fallback.user.address!.citytells the compiler you know better. It crashes at runtime if you are wrong.
Prefer the first two. Use ! only when another part of the template, such as an enclosing @if, already guarantees the value exists.
Expression Guidelines
Angular re-evaluates every binding on every change detection pass, and that can happen many times per second. Good expressions are:
- Free of side effects. Reading a value must not change application state. A method that logs, increments a counter, or calls an API will run far more often than you expect.
- Fast. Sorting a 10,000-item array inside
{{ }}runs that sort on every pass. Compute it once, or use acomputedsignal (covered in the next chapter). - Idempotent. If nothing changed, two evaluations in a row must return the same value.
Method calls such as subtotal() are fine when the method is cheap and pure. Signals are read with the same call syntax, count(), and they have the extra benefit of telling Angular exactly when their value changes.
Exercise
A component has order: { customer?: { name: string } } = {} and the template <p>{{ order.customer.name }}</p>. With strictTemplates on, what happens, and how would you show "Guest" when there is no customer?
Show answer
The build fails because order.customer is possibly undefined. Write {{ order.customer?.name ?? 'Guest' }}. Optional chaining returns undefined instead of throwing, and nullish coalescing replaces that undefined with 'Guest'.
Exercise
Which of these are valid template expressions? (a) {{ count + 1 }} (b) {{ count++ }} (c) {{ Math.floor(price) }} (d) {{ tags }} where tags is ['a', 'b'] (e) {{ new Date() }}
Show answer
(a) is valid. (b) is invalid because increment is an assignment. (c) fails because Math is a global and not in the expression context; expose it as a class field or wrap it in a method. (d) is valid and renders "a,b". (e) is invalid because new is not allowed.
Exercise
A template shows {{ shuffled() }}, where shuffled() returns a new randomly ordered copy of an array. In development the console shows ExpressionChangedAfterItHasBeenCheckedError. Explain why and fix it.
Show answer
Each call returns a new array in a different order, so the development-mode second check sees a different value. Shuffle once, for example when the data loads or in response to a button click, and store the result in a field or signal. Then the template reads a stable value.