Angular 2 Interpolation and Template Expressions

Interpolation uses template expressions in double curly braces to display data from the component class and template reference variables.

Updated Nov 2017, Angular version 5.0

Interpolation with Curly Braces

Double curly braces contain template expressions which allow us to read primitive or object values from component properties. Template expressions are similar to JavaScript and include features such as the ternary operator, concatenation and arithmetic.

If a nested object such as address is optional, use the safe navigation operator (?.) to avoid the dreaded Cannot read property 'city' of undefined.

person.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-person',
  template: `
    <h2>{{heading}}</h2>
    <p>
      Name: {{person.sex === 'm' ? 'Mr' : 'Ms'}}
      {{person.name.first + ' ' + person.name.surname}}
    </p>
    <p>City: {{person.address?.city}}</p>`
})
export class PersonComponent {

  heading = 'Person Details';

  person: any = {
    name: {
      first: 'Harry',
      surname: 'Angel'
    },
    sex: 'm'
  };
}

The Application

Here is the output from this component.

Template Reference Variables

Template expressions can access template reference variables too. A template reference variable is a reference to a DOM element or directive within a template. Here we read the values as numbers and use them to perform a couple of calculations.

We've seen that template expressions can read class properties but they can also call methods, including getter methods, on the class too.

calc.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-calc',
  template: `
    <h2>Calc</h2>
    <p>
      <input #num1 type="number" value="{{init.first}}" (input)="0">
      <input #num2 type="number" value="{{init.second}}" (input)="0">
    </p>
    <p>
      Sum: {{num1.valueAsNumber + num2.valueAsNumber}},
      Largest: {{max(num1.valueAsNumber, num2.valueAsNumber)}}
    </p>`
})
export class CalcComponent {

  get init(): any {
    return {
      first: 11,
      second: 22
    };
  }

  max(first: number, second: number): number {
    return Math.max(first, second);
  }
}

The Application

Here is the output from this component.

Escaping

Interpolation automatically escapes any HTML, so here {{html}} displays <div>this is a div</div>, or more precisely it displays &lt;div&gt;this is a div&lt;/div&gt;.

This helps to protect us from malicious attacks such as XSS by sanitizing any data that may contain script tags. For example, {{script}} displays <script>alert("danger!")</script>. It does not run the alert statement.

To add a raw HTML value to the page we bind to the innerHTML DOM property instead. Using this technique we get ✰✰✰✰, whereas with interpolation we get &#10032;a&#10032;&#10032;&#10032;. To find out more about binding to DOM properties such as innerHTML, see the Angular Property Binding tutorial.

escaping.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-escape',
  template: `
    <h2>Escape</h2>
    <p>{{html}}</p>
    <p>{{script}}</p>
    <p>
      For HTML, don't use {{stars}},
      use <span [innerHTML]="stars"></span> instead
    </p>
    <p>Evaluate: {{variable}}</p>
    <p ngNonBindable>Do not evaluate: {{variable}}</p>`
})
export class EscapingComponent {

  html = '<div>this is a div</div>';
  script = '<script>alert("danger!")</script>';
  variable = 'abc';

  get stars(): string {
    return '&#10032;'.repeat(4);
  }
}

Incidentally, if you don't want Angular to evaluate a template expression in double curly braces then add the ngNonBindable directive to the element.

The Application

Here is the output from this component.

Where Next?

To find out more about Angular and TypeScript, check out these tutorials.

  • Hello World - Implement a super-simple <hello-world> custom element using an Angular and TypeScript.
  • The Angular with TypeScript Tutorial - includes examples of components, template syntax, property binding, event binding, bootstrapping and more.
  • Configuration - Configure Angular and TypeScript to download dependencies from node modules or a CDN, and to compile the TypeScript during development or in the browser at runtime.
  • Templates - introduction to inline and external templates.
  • Property Binding - bind to DOM properties using square brackets and template expressions.
  • Event Binding - handle DOM events using parentheses and template statements.
  • Two-way Binding - combine property and event binding to create two-way binding with ngModel.
  • Input Binding - bind to <input> fields such as text, textarea, checkbox, radio and select.
  • Built-in Directives - see how to use built-in directives ngIf, ngSwitch, ngFor, ngClass and ngStyle.
  • Component Input Output - use @Input and @Output to pass data in to and out of a component.
  • Angular Router - Use the Angular router to navigate between components when the user clicks a link.
  • Nested Child Routes - An example of how child routes allow navigation between multiple views when a user clicks a link in a sub-menu.