← Learning Hub
Beginner

Templates and Binding

The template is the component's HTML. Angular adds special syntax to connect it to the class:

  • {{ value }} shows a value as text (interpolation).
  • [property]="value" sets an element property (property binding).
  • (event)="method()" runs a method when something happens (event binding).

Binding connects your class's data to the page and keeps them in sync. Interpolation ({{ }}) shows a value as text; when the value changes, the text updates. Property binding ([ ]) sets things like an image's src, a button's disabled, or a CSS class. Event binding (( )) runs your method when the user clicks, types or submits.

A simple way to remember: square brackets send data into the page, round brackets send events out of the page to your code.

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

@Component({
  selector: 'app-deal',
  template: `
    <h2>{{ name }}</h2>
    <img [src]="photo" [alt]="name" width="120" />
    <p>Price: Rs {{ price }}</p>
    <button (click)="buy()">Buy now</button>
  `,
})
export class Deal {
  name = 'Smart Watch';
  price = 2499;
  photo = 'watch.png';

  buy() {
    alert('Added ' + this.name + ' to cart');
  }
}
A template written across many lines goes inside backticks `...`. A short one can use normal quotes.
Key points
  • {{ value }} shows a value as text.
  • [property] binds data into an element.
  • (event) runs a method when something happens.

📝 Test yourself

1. What does {{ price }} do in a template?
2. Which syntax runs a method when a button is clicked?
3. Fill in the brackets that bind an image source:
<img ="photo" />