Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Template syntax and interpolation

An Angular template is ordinary HTML plus a few additions that connect the markup to the component class. The simplest of them is interpolation: a value from the class is inserted into the page text.

Interpolation

An expression in double curly braces is evaluated, and the result is shown as text. Take the to-do list component:

// src/app/todo-list/todo-list.ts
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-todo-list',
  templateUrl: './todo-list.html',
  styleUrl: './todo-list.css',
})
export class TodoList {
  owner = 'Anna';
}
<!-- src/app/todo-list/todo-list.html -->
<h2>Tasks: {{ owner }}</h2>

The page shows the heading "Tasks: Anna". The template sees all fields and methods of the class except those declared private.

Expressions

Inside the braces you can write short expressions: arithmetic, comparisons, the ternary operator, object properties and array elements.

// src/app/todo-list/todo-list.ts
export class TodoList {
  owner = 'Anna';
  total = 5;
  done = 2;
  tasks = ['Buy bread', 'Call Oleg'];
}
<!-- src/app/todo-list/todo-list.html -->
<h2>Tasks: {{ owner }}</h2>
<p>Left: {{ total - done }} of {{ total }}</p>
<p>{{ done === total ? 'All done' : 'Work to do' }}</p>
<p>First task: {{ tasks[0] }}</p>

The page shows "Left: 3 of 5", "Work to do" and "First task: Buy bread".

Calling methods

If a calculation is longer than one line, move it into a class method and call it in the template:

// src/app/todo-list/todo-list.ts
export class TodoList {
  total = 5;
  done = 2;
 
  progress() {
    return Math.round((this.done / this.total) * 100);
  }
}
<!-- src/app/todo-list/todo-list.html -->
<p>Done: {{ progress() }}%</p>

It shows "Done: 40%". Methods in a template must be fast and must not change anything — Angular calls them on every check of the page.

Safe output

Interpolation always outputs text. If a field holds the string '<b>important</b>', the page shows the characters with angle brackets, not bold text. This is how Angular protects against injected HTML.

What a template cannot do

Not allowedWhy
Assignment x = 5 in interpolationA template only reads data
new, ++, --Not supported by the template syntax
Math, console, windowA template sees only class members

Common mistake

{{ Math.round(price) }} looks like ordinary JavaScript, but the build fails with Property 'Math' does not exist. Global objects are not available in a template. Calculate the value in a class method or field, like progress() above.

Thanks for reading!

Donate to the site — we work hard for you.