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.
The four bindings
<!-- 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" />
[(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
<!-- 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 (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> }
}
| Old | New | Why it is better |
|---|---|---|
*ngIf | @if | Native @else if, better type narrowing, no import |
*ngFor | @for | track is mandatory, @empty built in, faster |
[ngSwitch] | @switch | No wrapper element needed |
CommonModule import | nothing | Control flow is part of the compiler |
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.
ng generate @angular/core:control-flow
@defer — lazy loading inside a template
@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.
| Trigger | Fires when | Good for |
|---|---|---|
on viewport | The placeholder scrolls into view | Below-the-fold widgets |
on idle | The browser is idle (default) | Nice-to-have content |
on interaction | Click or keydown on the placeholder | Accordions, tabs |
on hover | Pointer enters | Preview popovers |
on timer(3s) | After a delay | Rarely |
when expr | A signal or expression turns true | Feature flags, permissions |
prefetch on hover | Downloads early, renders later | Making 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
{{ 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' } }}
@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`;
}
}
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
<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.
<!-- 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);
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.