Sub topic 2
Displaying Values with Interpolation
Interpolation is the most common binding in Angular. It takes a value from your component and puts it into the page as text. This chapter covers how interpolation evaluates expressions and turns results into strings, and where its limits are.
This chapter assumes you know HTML and the DOM, TypeScript classes, and how to create and run a component with the Angular CLI. You should also have read the previous chapter on templates and template expressions.
The Basic Syntax
An interpolation is a template expression placed between double curly braces, {{ and }}. Angular evaluates the expression against the component instance, converts the result to a string, and writes it into the DOM.
import { Component } from '@angular/core';
@Component({
selector: 'app-welcome',
template: `
<h1>Welcome, {{ firstName }} {{ lastName }}</h1>
<p>You have {{ unread }} unread messages.</p>
<p>That is {{ unread * 2 }} if you count drafts twice.</p>
`,
})
export class WelcomeComponent {
firstName = 'Grace';
lastName = 'Hopper';
unread = 3;
}The rendered heading reads "Welcome, Grace Hopper". Angular does not rebuild the whole <h1> element when a value changes. At compile time it splits the text into static parts and dynamic parts. At runtime it updates only the text that depends on an expression whose value has changed.
Interpolation is one-way. Data moves from the component to the view, and nothing typed or changed in the view flows back into firstName. Later chapters cover the bindings that carry data in the other direction.
How Values Become Strings
Interpolation always produces text. Angular converts most values the way JavaScript's String() does, with one important exception: null and undefined render as an empty string instead of the words "null" and "undefined".
| Expression value | Rendered text |
|---|---|
| `'Ada'` | Ada |
| `42` | 42 |
| `0` | 0 |
| `false` | false |
| `null` | (empty) |
| `undefined` | (empty) |
| `NaN` | NaN |
| `[1, 2, 3]` | 1,2,3 |
| `{ id: 1 }` | [object Object] |
| `new Date(2026, 0, 5)` | Mon Jan 05 2026 00:00:00 GMT... (locale and zone dependent) |
Some of these results surprise people:
0andfalseare printed. They are not treated as empty. If you want "none" instead of0, write that logic yourself, for example{{ count || 'none' }}.- Objects print
[object Object]. To inspect an object while debugging, use thejsonpipe:{{ user | json }}. - Dates use the browser's default
toString()output, which is long and depends on the locale. Use thedatepipe for any date that users will see.
import { Component } from '@angular/core';
import { DatePipe, JsonPipe } from '@angular/common';
@Component({
selector: 'app-formatting',
imports: [DatePipe, JsonPipe],
template: `
<p>Raw: {{ created }}</p>
<p>Formatted: {{ created | date: 'mediumDate' }}</p>
<pre>{{ settings | json }}</pre>
`,
})
export class FormattingComponent {
created = new Date(2026, 0, 5);
settings = { theme: 'dark', fontSize: 14 };
}What You Can Write Inside the Braces
The content of {{ }} is a template expression. It looks like JavaScript but is a deliberately restricted subset.
Allowed:
- Property access and method calls on the component:
{{ user.name }},{{ fullName() }} - Arithmetic, comparison and logical operators:
{{ price * qty }},{{ a > b }},{{ isAdmin && 'Admin' }} - The ternary operator:
{{ online ? 'Online' : 'Offline' }} - Optional chaining and nullish coalescing:
{{ user?.address?.city ?? 'Unknown' }} - Pipes:
{{ title | uppercase }} - Array and object literals:
{{ [a, b].length }} - Template reference variables and loop variables declared in the template
Not allowed:
- Assignments such as
=,+=or-= - Increment and decrement:
++and-- - The
newoperator - Statement chaining with
; - Bitwise operators
|and&, because|means "pipe" in a template - Global objects such as
window,document,Math,JSONorconsole
Recent Angular versions have added some JavaScript syntax to templates, such as typeof and template literals. Check the version your project uses before relying on newer syntax.
The rule about globals trips up many developers. Expressions are evaluated against the component instance, not against the global scope, so {{ Math.round(score) }} fails. Expose what you need on the class instead:
import { Component } from '@angular/core';
@Component({
selector: 'app-score',
template: `<p>Score: {{ round(score) }}</p>`,
})
export class ScoreComponent {
score = 87.6;
round = Math.round;
}Handling Missing Data
Data often arrives late, for example from an HTTP request. Suppose user starts as undefined and is filled in later:
import { Component } from '@angular/core';
interface User {
name: string;
address?: { city: string };
}
@Component({
selector: 'app-user-card',
template: `
<p>Name: {{ user?.name }}</p>
<p>City: {{ user?.address?.city ?? 'Not provided' }}</p>
`,
})
export class UserCardComponent {
user?: User;
constructor() {
setTimeout(() => {
this.user = { name: 'Linus' };
}, 1000);
}
}Without ?., the expression user.name would throw a TypeError at runtime while user is still undefined. With strict template type checking (strictTemplates, which the CLI turns on by default for new projects), the compiler reports this as an error before the app runs.
The non-null assertion operator ! is also available. {{ user!.name }} tells the type checker that user is defined. It changes only the type check, not the runtime behavior, so use it only when you are certain the value exists.
Interpolation in Attributes
You can also use interpolation inside an attribute value:
import { Component } from '@angular/core';
@Component({
selector: 'app-photo',
template: `
<img src="{{ photoUrl }}" alt="Photo of {{ name }}">
<a href="/users/{{ userId }}/profile">Profile</a>
`,
})
export class PhotoComponent {
photoUrl = '/assets/linus.png';
name = 'Linus';
userId = 42;
}Angular does not set the HTML attribute here. The compiler rewrites each interpolated attribute as a property binding on the DOM property with the same name. src="{{ photoUrl }}" behaves like [src]="photoUrl". When static text is mixed in, as in alt="Photo of {{ name }}", the result is the concatenated string.
That rewriting causes a common error. If no DOM property matches the attribute name, compilation fails:
import { Component } from '@angular/core';
@Component({
selector: 'app-broken-cell',
template: `
<table><tr>
<!-- Error: Can't bind to 'colspan' since it isn't a known property of 'td' -->
<td colspan="{{ span }}">Total</td>
</tr></table>
`,
})
export class BrokenCellComponent {
span = 2;
}The DOM property is colSpan, with a capital S, and Angular will not guess. The fix is to target the attribute explicitly with attr.colspan="{{ span }}" or [attr.colspan]="span". The chapter on attribute, class and style bindings explains why.
Interpolation or Property Binding?
For string values, src="{{ url }}" and [src]="url" do the same thing. The difference shows up with values that are not strings. Interpolation always produces a string, while property binding passes the value through unchanged.
| Case | Interpolation | Property binding |
|---|---|---|
| Plain text content | Natural choice | Use `[textContent]` only for special cases |
| String attribute such as `src` or `alt` | Works | Works |
| Mixing static text and values | Concise: `"/users/{{ id }}"` | Needs concatenation |
| Boolean property such as `disabled` | Wrong: sets the string `"false"`, which counts as true | Correct |
| Object or array passed to a child input | Wrong: becomes a string | Correct |
Never combine the two forms. [src]="{{ url }}" is a template parse error, because the inside of square brackets is already an expression.
Performance: Method Calls and Getters
Angular re-evaluates every interpolation each time change detection checks the component. A method call such as {{ total() }} runs on every check, not only when its inputs change.
import { Component } from '@angular/core';
interface Line {
price: number;
qty: number;
}
@Component({
selector: 'app-cart',
template: `<p>Total: {{ total() }}</p>`,
})
export class CartComponent {
lines: Line[] = [
{ price: 10, qty: 2 },
{ price: 5, qty: 4 },
];
total() {
return this.lines.reduce((sum, l) => sum + l.price * l.qty, 0);
}
}For a small list this costs nothing worth worrying about. For expensive work, such as sorting large arrays or heavy formatting, use one of these approaches instead:
- Compute the value once when the data changes and store it in a field.
- Use a pure pipe. Angular re-runs a pure pipe only when its input reference changes.
- Use a
computed()signal. Signals are covered in a later chapter. Reading a signal in a template looks like a method call,{{ count() }}, but the result is memoized and only recalculated when a dependency changes.
Common Mistakes at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| `[object Object]` on screen | Interpolating an object | Interpolate a property, or use the `json` pipe |
| Blank text where you expected "null" | `null` and `undefined` render as empty | Use `?? 'fallback'` |
| `TypeError: Cannot read properties of undefined` | Data not loaded yet | Use `?.` |
| "Can't bind to 'x' since it isn't a known property" | Interpolated attribute has no matching DOM property | Use `attr.x` |
| Button stays disabled | `disabled="{{ flag }}"` sets a string | Use `[disabled]="flag"` |
| "Math is not defined" or a similar error | Global referenced in a template | Expose it on the class |
Exercise
A component has stock = 0 and note: string | null = null. What does the template <p>Stock: {{ stock }}, Note: {{ note }}</p> render, and how would you show "Out of stock" when stock is 0 and "None" when note is null?
Show answer
It renders "Stock: 0, Note: " because 0 converts to "0" and null renders as an empty string. Use {{ stock === 0 ? 'Out of stock' : stock }} and {{ note ?? 'None' }}. Avoid stock || 'Out of stock' only if you might later treat other falsy values differently. For a number it gives the same result here, but the explicit comparison states the intent.
Exercise
Why does <td colspan="{{ cols }}"> fail to compile while <img src="{{ url }}"> works, and what is the smallest change that fixes the first one?
Show answer
Angular rewrites interpolated attributes as property bindings. The img element has a src DOM property, but td has no property named colspan (its property is colSpan), so the compiler reports an unknown property. Writing attr.colspan="{{ cols }}" tells Angular to set the HTML attribute instead.
Exercise
A teammate writes <button disabled="{{ isLocked }}">Save</button> with isLocked = false, and the button is still disabled. Explain why and correct it.
Show answer
Interpolation converts the value to the string "false". Assigning any non-empty string to the boolean disabled property makes it true. Use a property binding so the boolean passes through unchanged: <button [disabled]="isLocked">Save</button>.