Follow by Email

Angular 2 - Interpolation and the expression context

Angular allows us to mark up our template code to get more use out of it. Angular has a template syntax that it supports, which is made up of interpolation, binding, expressions, conditional templating, template variables, and template expression operators. 

Interpolation is a way to get data displayed in the view. Let's head over to the media-item.component.html file and check out interpolation in action. You do interpolation by using a pair of matching curly braces in the markup. And the contents of the double curly braces is a JavaScript-like expression that Angular will evaluate and then convert to a string. So we can add a pair of curly braces in the H tag for the media item name and put an expression.

 But not all expressions are supported. Assignments, newing up variables, expressions that are chained, and incrementers and decrementers are not valid template expressions. The most common use of interpolation is to display some data from a property we have set on the component class. If we switch over to the media-item.component.ts file and add a class property named "name" and assign it a string value of "the redemption" we can then flip back over to the template file and put "name" in our curly braces in place of the text expression. 

In media-item.component.html :

<h2>{{ name }}</h2>
<div>{{ wasWatched() }}</div>
<div class="tools">

In media-item.component.ts :

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

  selector: 'mw-media-item',
  templateUrl: 'app/media-item.component.html',
  styleUrls: ['app/media-item.component.css']
export class MediaItemComponent {
  name = 'The Redemption';

  wasWatched() {
    return true;

Notice that we use the property "name" directly in the interpolation statement without any this.reference or some other component instance reference. 

Angular makes all properties on the component class available to the template when it processes it. So back in the browser, we can see that the name text gets rendered in the H tag. This component property is made available via what is known as the expression context. Methods on the component class are also available in the expression context. So in the media-item.component.ts file, we can add a method named "was watched" to our component class. And we can have it return true. And then over in the template markup, we can replace the static "watched on date" text with a pair of curly braces and a called with a method. And then over in the browser, we can see true is rendered.