Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 74 ยท Templates and Data Binding

Interpolation and Template Expressions

Learn Angular interpolation with double curly braces, which expressions templates allow, safe navigation, nullish coalescing, pipes and template reference variables.

The simplest way to put data on an Angular page is interpolation: you write an expression between double curly braces, and Angular replaces it with the value as text. It is the first of several data bindings you will meet in this chapter. Interpolation is easy to start with, but there are rules about what may go inside the braces, and a few handy operators that make templates shorter and safer.

The examples of real Angular below are read-only; run them in a project from the setup lesson. The Try it editors contain a hand-written stand-in for a template engine, so you can experiment with the same rules.

Interpolation: {{ }}

Inside a component's template, {{ expression }} is evaluated against the component instance:

TypeScript
import { Component } from '@angular/core';

@Component({
  selector: 'app-profile',
  template: `
    <h2>{{ user.name }}</h2>
    <p>{{ user.age }} years old, next year {{ user.age + 1 }}.</p>
    <p>{{ greeting() }}</p>
  `,
})
export class Profile {
  user = { name: 'Ada Lovelace', age: 36 };

  greeting(): string {
    return `Hello, ${this.user.name}`;
  }
}

You can read properties, call methods and do arithmetic. If your state lives in a signal (see the signals lesson), you call it like a function: {{ count() }}.

The result is converted to a string and inserted as text, not as HTML. If a value contains <b>bold</b>, the visitor sees the angle brackets, not bold text. That makes interpolation safe against script injection by default; we come back to the exceptions in the property binding lesson.

flowchart LR
  E["Expression<br/>in the template"] --> V["Evaluated against<br/>the component"]
  V --> P["Pipes<br/>transform the value"]
  P --> S["Converted to a string"]
  S --> X["Written as a text node<br/>(HTML-escaped)"]

Interpolation turns an expression into text; the browser never parses the result as markup.

null and undefined become an empty string, so a missing value leaves a blank space instead of printing "undefined". Objects become [object Object], which is rarely what you want; use the json pipe while debugging.

Interpolation inside attributes

You can also write interpolation in an attribute value, as in <img src="/photos/{{ id }}.jpg">. Angular treats it as a property binding with a string result. Prefer the explicit [src] form when the value is not a string, which the next lesson covers.

What an expression may contain

A template expression looks like JavaScript, but it is a restricted subset, deliberately. Expressions run every time Angular checks the view, so they must be fast and free of side effects. In general you may use:

  • Property reads and method calls on your component (user.name, total()).
  • Literals: numbers, strings, true, false, null, arrays and objects. Recent versions also accept template literals and typeof; check the docs for the version you use.
  • Arithmetic, comparison and logical operators, and the conditional operator cond ? a : b.
  • The safe navigation operator ?., nullish coalescing ??, and the non-null assertion !.
  • Pipes, written with |, which are Angular's own addition.

You may not use:

  • Assignment (=, +=) and increment (++, --), except inside event handlers (see event binding).
  • new, import or statements such as if and for (use the @if and @for blocks from the control flow lesson).
  • Chaining with ; or ,.
  • Global names like window, document or Math. A template can only see the members of its component (and template variables). To use Math.round, expose a method or a property from the class.

Do not put slow or side-effecting work in an expression. Angular may evaluate it many times, in an order you do not control. A method that logs, fetches or sorts a big array in the template is a bug waiting to happen. Compute values once, with a computed signal or a pure pipe.

Safe navigation and nullish values

A common problem is a value that is null until data arrives. {{ user.address.city }} throws if address is null, and the page fails to update. The safe navigation operator ?. short-circuits to undefined instead:

HTML
<p>City: {{ user.address?.city }}</p>

Combine it with nullish coalescing ?? to show a fallback only when the left side is null or undefined:

HTML
<p>City: {{ user.address?.city ?? 'Unknown' }}</p>
<p>Nickname: {{ user.nickname ?? user.name }}</p>

?? differs from ||: it keeps 0 and the empty string. That is usually what you want for numbers and text.

The non-null assertion ! tells the type checker a value is not null (user!.name). It does not change the behavior at runtime, so it only silences a compile-time complaint. Use it only when you are certain.

Pipes in expressions

A pipe transforms a value for display:

HTML
<p>{{ price * quantity | currency }}</p>
<p>{{ name | uppercase }}</p>
<p>{{ created | date: 'mediumDate' }}</p>

The pipe operator has the lowest precedence, so in the first line the multiplication happens first and the whole result is formatted. Use parentheses when you want a pipe to apply to part of an expression. The pipes lesson covers the built-in pipes and how to write your own.

Template reference variables

You can name an element inside the template with #, and use that name anywhere else in the same template:

HTML
<input #city placeholder="City" />
<button (click)="save(city.value)">Save</button>
<p>You typed {{ city.value }}</p>

#city is a template reference variable. On a plain element it refers to the DOM element, so city.value is the input's current text. On a component it refers to the component instance. The variable is visible in the whole template but not in other components' templates. Note that the interpolation updates when Angular next checks the view, which is after events such as typing, so it follows the input as you type.

Stand-in: a template engine with the same rules

Here is a simplified template evaluator. It supports property paths, ?., ??, one arithmetic operator, three pipes and text escaping, and it throws when you read a property of null, like the real runtime does. It is not Angular's parser, but it follows the same rules, so you can see where ?., ?? and | apply.

TypeScript A stand-in template engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check each line against the rules: the <b> in the name is escaped, so it prints as text; a null nickname leaves an empty pair of brackets; ?. plus ?? produces Unknown; the pipe sees the product, not just quantity. Removing the ?. from the city line reproduces the crash shown at the end.

Expressions run on every check

Because Angular evaluates every expression each time it checks the view, an expensive method called in a template runs again and again. The second stand-in counts the calls. One version calls a method in every pass; the other caches the result until the data object is replaced, which is the idea behind a computed signal (explained in the signals chapter).

TypeScript A stand-in: method in the template vs a cached value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The plain method runs five times for five checks, the cached version once, and once more after the items change. In a real application there may be hundreds of checks per second, so it pays to keep expressions trivial.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does {{ name }} do in a template?

    Interpolation evaluates the expression against the component and writes the result as an escaped text node.
  2. 2. Which of these is NOT allowed in a template expression?

    Assignments are not allowed in interpolation because expressions must not have side effects. They are only allowed in event handlers.
  3. 3. What is the value of {{ qty ?? 5 }} when qty is 0?

    The nullish coalescing operator replaces only null and undefined. Zero is kept, unlike with the logical OR operator.
  4. 4. Why should you avoid calling an expensive method inside {{ }}?

    The expression runs every time the view is checked. Compute the value once and reuse it, for example with a computed signal or a pure pipe.
  5. 5. What does a template reference variable such as #city on an input element refer to?

    On a plain element the variable is the DOM element itself, so city.value reads the current text. On a component it refers to the instance.

Summary

  • {{ expression }} evaluates against the component and inserts the result as escaped text; null and undefined become an empty string.
  • Expressions are a restricted JavaScript subset: no assignments (except in event handlers), no new, no statements, no globals such as window.
  • Use ?. to avoid errors on missing data and ?? for fallbacks that keep 0 and empty strings.
  • The pipe operator | formats values and has the lowest precedence; use parentheses to limit it.
  • #name creates a template reference variable that points at an element (or a component instance) inside the same template.
  • Expressions run on every check, so keep them cheap and side-effect free.

Next: Property, Attribute, Class and Style Binding