Chapter 04

Templates, binding and control flow

Angular templates are HTML with four extra ideas. Learn the four and you can read any Angular template ever written.

⏱ 15 min readLevel: beginnerCore chapter

The four bindings

all of the syntax, in one block
<!-- 1 · interpolation: component → DOM text -->
<h2>{{ order().reference }}</h2>

<!-- 2 · property binding: component → DOM property -->
<button [disabled]="saving()">Save</button>
<img [src]="order().thumbnailUrl" [alt]="order().reference">
<app-badge [status]="order().status" />

<!-- 3 · event binding: DOM → component -->
<button (click)="save()">Save</button>
<input (keyup.enter)="search()" (blur)="touched.set(true)">

<!-- 4 · two-way: both directions (property + event, by convention) -->
<input [(ngModel)]="query">
<app-panel [(expanded)]="isOpen" />
The banana in a box

[(x)] is not new syntax — it is [x] plus (xChange). Remember it as "banana in a box": the parentheses go inside the brackets.

Attributes, classes and styles

the special cases
<!-- attribute binding: for things that are not DOM properties -->
<td [attr.colspan]="span()"></td>
<button [attr.aria-label]="'Cancel ' + order().reference"></button>

<!-- single class, conditionally -->
<tr [class.is-overdue]="isOverdue()">

<!-- several at once -->
<tr [class]="{ 'is-overdue': isOverdue(), 'is-paid': isPaid() }">

<!-- single style, with a unit suffix -->
<div [style.width.%]="progress()">
<div [style.color]="isOverdue() ? 'red' : null">

[attr.x] exists because colspan, aria-* and data-* are HTML attributes with no matching JavaScript property. If a plain property binding silently does nothing, this is usually why.

Built-in control flow

@if / @for / @switch
@if (loading()) {
  <app-spinner />
} @else if (error()) {
  <app-error [message]="error()!" (retry)="reload()" />
} @else {
  <table>
    @for (order of orders(); track order.id; let i = $index, isLast = $last) {
      <tr [class.last]="isLast">
        <td>{{ i + 1 }}</td>
        <td>{{ order.reference }}</td>
      </tr>
    } @empty {
      <tr><td colspan="2">No orders match your filter.</td></tr>
    }
  </table>
}

@switch (order().status) {
  @case ('PAID')    { <span class="ok">Paid</span> }
  @case ('PLACED')  { <span class="warn">Awaiting payment</span> }
  @default          { <span>{{ order().status }}</span> }
}
OldNewWhy it is better
*ngIf@ifNative @else if, better type narrowing, no import
*ngFor@fortrack is mandatory, @empty built in, faster
[ngSwitch]@switchNo wrapper element needed
CommonModule importnothingControl flow is part of the compiler
track is not optional, and the value matters

track order.id lets Angular reuse DOM nodes when the list changes. Using track $index on a list that reorders or filters will reuse the wrong nodes — focus jumps, inputs keep the previous value, animations play on the wrong row. Track a stable identity; use $index only for lists of primitives that never reorder.

terminal — migrate an existing codebase
ng generate @angular/core:control-flow

@defer — lazy loading inside a template

order-detail.component.html
@defer (on viewport) {
  <app-order-timeline [orderId]="order().id" />
} @placeholder (minimum 300ms) {
  <div class="skeleton" style="height:220px"></div>
} @loading (after 100ms; minimum 400ms) {
  <app-spinner />
} @error {
  <p>Could not load the timeline.</p>
}

Everything inside a @defer block — the component, its imports, its dependencies — is moved into a separate JavaScript chunk and fetched only when the trigger fires.

TriggerFires whenGood for
on viewportThe placeholder scrolls into viewBelow-the-fold widgets
on idleThe browser is idle (default)Nice-to-have content
on interactionClick or keydown on the placeholderAccordions, tabs
on hoverPointer entersPreview popovers
on timer(3s)After a delayRarely
when exprA signal or expression turns trueFeature flags, permissions
prefetch on hoverDownloads early, renders laterMaking an interaction feel instant

A heavy chart library that only appears on one tab is the canonical use. Moving it behind @defer (on interaction) can take 300 KB off the initial bundle for one line of template.

Pipes

built-in and custom
{{ order().total | currency:'EUR':'symbol':'1.2-2' }}
{{ order().placedAt | date:'dd MMM yyyy, HH:mm' }}
{{ order().reference | uppercase }}
{{ order().notes | slice:0:120 }}
{{ payload() | json }}                        <!-- debugging only -->
{{ count() | i18nPlural: { '=0': 'No orders', '=1': 'One order', 'other': '# orders' } }}
a custom pipe
@Pipe({ name: 'timeAgo', standalone: true, pure: true })
export class TimeAgoPipe implements PipeTransform {
  transform(value: string | Date): string {
    const seconds = (Date.now() - new Date(value).getTime()) / 1000;
    if (seconds < 60)    return 'just now';
    if (seconds < 3600)  return `${Math.floor(seconds / 60)} min ago`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)} h ago`;
    return `${Math.floor(seconds / 86400)} d ago`;
  }
}
Never write an impure pipe

pure: false makes the pipe run on every change detection cycle — potentially thousands of times a second. If you need to filter or sort a list, do it in a computed() in the component, where it is calculated once per change.

Template reference variables

#ref
<input #search (keyup.enter)="onSearch(search.value)" placeholder="Reference">
<button (click)="search.focus()">Focus</button>

<!-- on a component, the variable is the component instance -->
<app-order-form #form />
<button [disabled]="form.invalid()" (click)="form.submit()">Save</button>

Template security

Angular escapes interpolated values by default. {{ userInput }} can never execute a script — the framework treats it as text.

the dangerous escape hatch
<!-- sanitised: script tags and event handlers are stripped -->
<div [innerHTML]="descriptionHtml()"></div>

<!-- bypassing sanitisation — only ever for content YOU produced -->
this.trusted = this.sanitizer.bypassSecurityTrustHtml(ownTemplate);
bypassSecurityTrust* is an XSS decision

Every call is you telling Angular "I have proven this is safe". If the value came from a user, an API you do not control, or a database row a user can edit, it is not safe. Sanitise on the server or render as text.

A filtered list re-renders with the wrong rows keeping focus. Most likely cause?

Tracking by index tells Angular that position identifies a row. Filter the list and position 0 is now a different order, so Angular reuses the existing DOM node and only patches the text — leaving focus, scroll position and input state on the wrong row.