Templates and Data Binding

Templates and Data Binding in Angular: Picture a machinist standing at the control panel of a CNC milling machine.

The Analogy: A CNC Machine-Shop Operator Panel

Picture a machinist standing at the control panel of a CNC milling machine. Bolted to the panel is a digital readout, the DRO, that continuously shows the live position of each axis in thousandths of an inch. The machinist never writes on that readout; it is a window onto the machine's internal state. Whatever the controller believes the X axis position to be, the DRO shows it, and when the controller updates that number the display refreshes the same instant. This is exactly Angular interpolation: {{ position }} is a read-only pane of glass over a value living in the component class, redrawn for you whenever the class changes.

Beside the readout sits a numeric entry field where the operator keys in a target coordinate before a move. Setting that field pushes a value from the operator INTO the controller, one direction only, the way property binding [value]="target" pushes a class value into an element property. Nearby, the big green CYCLE START button does the reverse: pressing it sends a signal FROM the panel back into the controller to begin the program. That is event binding, (click)="run()" - the view telling the class that something happened. Reading a value out and sending an action in are two separate, one-way channels, and a disciplined panel keeps them visibly distinct so nobody confuses looking at a number with commanding one.

The most powerful control on the panel is the manual pulse generator, the MPG handwheel. Turn it and two things move in perfect lockstep: the physical axis advances AND the DRO number counts up to match, because the handwheel is wired so the machine's position and the displayed position are always the same value flowing both ways at once. This is two-way binding, [(ngModel)]="offset" - the union of a property binding in and an event binding out, so that editing the input updates the class and changing the class updates the input, with neither one ever lagging the other.

The failure mode is the cautionary tale every shop teaches on day one: leaving the handwheel engaged during an automatic program run. Now two authorities are driving the same axis at once - the running G-code and the operator's stray hand on the wheel - and they fight, jerking the position back and forth and often faulting the controller outright. Angular has the same hazard: when a two-way bound value is mutated by the class during the very change-detection pass that is trying to render it, the framework notices that the value it just read no longer matches and throws ExpressionChangedAfterItHasBeenCheckedError. One binding, one authority; let either the program or the handwheel drive, never both.


Syntax or Core Structure

A template is HTML annotated with binding syntax. The simplest binding is interpolation: a pair of double curly braces that evaluates a template expression and drops its stringified result into the DOM. The expression reads from the component instance, so the class is the single source of truth and the template is a live projection of it.

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

@Component({
  selector: 'app-badge',
  template: `
    <span class="badge">{{ label }}: {{ score }}</span>
    <span class="pass">Passing: {{ score >= 60 }}</span>
  `
})
export class BadgeComponent {
  label = 'Quiz';
  score = 72;
}

Angular evaluates each pair of braces as a JavaScript-like expression against the component, coerces the result to a string, and inserts it. {{ label }} and {{ score }} read fields directly, while {{ score >= 60 }} evaluates a comparison and renders the resulting boolean as text. Modelling that fold from state to rendered string in plain functions produces the exact strings Angular would show:

Quiz: 72
Passing: true

Angular does not interpret braces at runtime by scanning strings; the template compiler parses each binding ahead of time and emits imperative instructions that read the named fields and patch precisely those DOM nodes when a value changes. That is why a typo inside {{ }} surfaces as a build-time template error rather than a silent blank, and why interpolation always coerces its result to a string - a null or undefined renders as the empty string, while an object renders as the unhelpful [object Object] unless you format it first.

Interpolation is one-way and read-only: it can display score, but it can never assign to it. To change class state you need event binding, and to keep an input and a field in sync you need two-way binding. Those three directions - in, out, and both at once - are the whole of Angular's data-binding vocabulary, and every template you will ever write is assembled from them.


Technical Depth: The Four Binding Directions

Angular's binding syntax is small and orthogonal. Each form is defined by which way data flows and by the punctuation that marks it. Learning to read the punctuation itself as a direction arrow is the fastest way to become fluent in templates, because the brackets and braces announce the flow before you even read the expression inside them.

SyntaxNameDirectionData flow
{{ expr }}InterpolationOne-wayClass to view
[prop]="expr"Property bindingOne-wayClass to view
(event)="stmt"Event bindingOne-wayView to class
[(ngModel)]="p"Two-wayTwo-wayBoth ways

Interpolation and property binding (class to view)

Interpolation and property binding both carry data from the class into the view; they differ only in target. Interpolation writes into text content, while property binding sets a DOM property. [src]="url" assigns to the element's live src property, not its src attribute - a crucial distinction, because properties are live and typed while attributes are merely the initial string parsed from the HTML. Binding [disabled]="isBusy" sets the real boolean DOM property; writing disabled="{{ isBusy }}" instead coerces to the string "false", which is still truthy and leaves the button stuck disabled. A related safeguard is the safe-navigation operator: {{ user?.name }} renders nothing instead of throwing when user is null, which matters because interpolation runs during change detection long before asynchronous data has arrived.

Event binding (view to class)

Event binding runs a template STATEMENT when a DOM event fires. (click)="score = score + 1" mutates the class in response to the view. The special $event variable exposes the event payload, so (input)="onType($event)" hands the raw DOM event to a method. Statements are allowed side effects - that is their entire purpose - which is exactly the opposite of expressions, discussed just below. A template reference variable, declared with #box on an element, gives a statement direct access to that element, so (click)="save(box.value)" reads the live input without any extra binding - yet that #box name exists only inside the template and is invisible to the component class.

Two-way binding is sugar

[(ngModel)]="name" looks like a new primitive but is pure syntactic sugar - the "banana in a box" - expanding to a property binding plus an event binding: [ngModel]="name" (ngModelChange)="name = $event". Understanding the expansion demystifies it: there is no third kind of data flow, only an in and an out bound to the same field. Note that ngModel requires FormsModule; forget the import and the brackets bind to nothing at all. Because the expansion is literally a property binding plus an event binding, you can always drop back to the two explicit halves whenever you need to intercept the change - to validate, clamp, or transform the value before storing it - which the fused [(ngModel)] alone gives you no seam to do.

Expressions versus statements

Template EXPRESSIONS (interpolation and property binding) must be free of side effects and are re-evaluated on every change-detection pass, so they must be cheap. Template STATEMENTS (event bindings) are permitted side effects but run only when their event fires. A getter feeding a binding is acceptable when it stays trivial:

@Component({
  selector: 'app-cart',
  template: `
    <p>Total: {{ total }}</p>
  `
})
export class CartComponent {
  items = [
    { price: 10, qty: 2 },
    { price: 5, qty: 3 }
  ];
  get total(): number {
    return this.items.reduce((sum, it) => sum + it.price * it.qty, 0);
  }
}

The getter folds the line items into a single number the instant the template asks for total:

Total: 35

Because that getter runs on every change-detection pass, it must stay cheap; a heavy computation hidden behind an innocent-looking binding is a performance trap addressed in the Best Practices below. The same rule governs interpolation itself: the compiler cannot memoize a method call, so {{ formatDate(now) }} is recomputed on every pass, whereas a pure pipe such as {{ now | date }} caches its result until the input reference actually changes.


Real World Example: A Temperature Converter

Consider a converter that shows a Celsius input alongside its Fahrenheit equivalent and a reference table of common values. It uses interpolation for the two readouts, a plain method for the conversion, and *ngFor to render the sample rows from an array on the class.

@Component({
  selector: 'app-temp',
  template: `
    <label>Celsius:
      <input type="number" [(ngModel)]="celsius">
    </label>
    <p>{{ celsius }}C = {{ toF(celsius) }}F</p>
    <table>
      <tr *ngFor="let c of samples">
        <td>{{ c }}C = {{ toF(c) }}F</td>
      </tr>
    </table>
  `
})
export class TempComponent {
  celsius = 25;
  samples = [0, 25, 37, 100];
  toF(c: number): number {
    return c * 9 / 5 + 32;
  }
}

Folding the sample list through the same toF formula that the template calls reproduces the reference table exactly as it renders in the DOM:

0C = 32F
25C = 77F
37C = 98.6F
100C = 212F

Now suppose a developer decides the Fahrenheit readout should itself be editable, binds it two-way, and rounds it to a whole degree for a tidy display. Each edit then pushes the rounded value back through the inverse formula into celsius, and the round-trip no longer lands where it started:

let celsius = 37;
let fahrenheit = Math.round(celsius * 9 / 5 + 32);
let back = (fahrenheit - 32) * 5 / 9;
console.log('start C:', celsius);
console.log('rounded F:', fahrenheit);
console.log('back to C:', back);
start C: 37
rounded F: 99
back to C: 37.22222222222222

The genuine design flaw lives in the shown component itself: toF is a method invoked directly from the template, once for the live celsius value and once for every row of samples. Angular cannot know the result is stable, so it re-runs toF for all four rows on every single change-detection pass - every keystroke anywhere on the page, every timer tick, every emitted event. With four rows the cost is invisible; with four thousand it becomes a visible stutter. The *ngFor also lacks a trackBy, so any replacement of the samples array tears down and rebuilds every row rather than reusing the unchanged ones. The remedy, covered next, is to precompute the rows into a bound array or move the conversion into a pure pipe that memoizes on its input, and to add a trackBy. The round-trip snippet above is the second warning: a value shown on screen must never be the very same variable as the value you store when the two can differ in precision, or an innocent bit of rounding will silently corrupt the source of truth one edit at a time.


Common Mistakes

  1. Confusing attributes with properties. Writing disabled="{{ flag }}" sets the literal string "false", which is truthy; use [disabled]="flag" to bind the real boolean DOM property.
  2. Forgetting FormsModule for ngModel. Without importing it, [(ngModel)] silently binds to nothing and the input never syncs with the class.
  3. Putting side effects in an interpolation. {{ items.push(x) }} mutates state while rendering and will either do nothing useful or trigger ExpressionChangedAfterItHasBeenCheckedError.
  4. Calling expensive methods from the template. A binding like {{ computeReport() }} re-runs on every change-detection pass, not once, so heavy work belongs in a field or a pure pipe.
  5. Assuming interpolation can write back. {{ }} is strictly one-way display; to change a field you must use an event binding or a two-way binding.
  6. Mixing up the banana-in-a-box brackets. ([ngModel]) and [(ngModel)] are not the same; only [( )] is two-way, and swapping the order silently breaks the binding.
  7. Rounding a value on one side of a two-way binding. When the displayed value differs in precision from the stored one, every round-trip corrupts the source, as the converter above demonstrates.
  8. Omitting trackBy in *ngFor. Without it, replacing the backing array rebuilds every DOM node instead of reusing the ones whose identity did not change.
  9. Referencing template-local variables in the class. A variable declared with #ref or a let in the template does not exist on the component instance and cannot be read from TypeScript.

Best Practices

  • Keep template expressions trivial - field reads, simple comparisons, and property access - so that change detection stays cheap on every pass.
  • Move any real computation out of the template into a component field, a genuinely light getter, or a pure pipe rather than a method call.
  • Read the binding punctuation as a direction: [ ] means data in, ( ) means events out, [( )] means both, and {{ }} means display.
  • Prefer property binding [prop]="expr" over interpolation inside attributes whenever the value is not a string, so its type is preserved.
  • Import FormsModule (or ReactiveFormsModule) explicitly in every module or standalone component that uses ngModel.
  • Never let the on-screen copy of a value and its stored copy be the same two-way-bound field when they can differ in precision or format.
  • Add a trackBy function to every *ngFor over data that can change, keying it on a stable unique identity.
  • Keep event-binding statements to a single expression; delegate anything longer to a named method on the component class.

Practice Exercises

  1. Build a live character counter. Bind a text <input> two-way to a message field and interpolate {{ message.length }} beside it so the count updates as you type.
  2. Toggle a panel with event binding. Add a button whose (click) flips an isOpen boolean, then use [hidden]="!isOpen" to show or hide a paragraph without removing it from the DOM.
  3. Extend the temperature converter. Add a Kelvin column to the reference table by writing a second pure method toK(c) and interpolating it in a new cell of every *ngFor row.
  4. Expose the ngModel expansion. Replace a [(ngModel)]="name" binding with its explicit [ngModel]="name" (ngModelChange)="name = $event" form and confirm the input still behaves identically.