Templates in Angular
What a template is
Section titled “What a template is”An Angular template is not HTML with string substitution. It is compiled to instructions that create and update DOM, and its expression language is a deliberately restricted subset of JavaScript. Understanding the restrictions — and why they exist — makes most template errors self-explanatory.
The core principle: templates are trusted and treated as executable code, while the values you bind into them are untrusted and sanitized. That asymmetry drives the security model, and it is why a template must never be built by concatenating user input. See Angular Security.
Expressions are not JavaScript
Section titled “Expressions are not JavaScript”Supported literals: strings, booleans, numbers, object and array literals, null, regular expressions, and template strings (including tagged ones). BigInt is not supported.
Globals: only undefined and $any. No Number, Boolean, NaN, Infinity, parseInt, Math, JSON, Date — none of them. Expose what you need from the component class.
Supported operators cover most of what you would write: arithmetic and exponentiation, comparison, logical, nullish coalescing, ternary, property access, typeof, void, in, instanceof, spread and rest, and the assignment family (in event statements). Plus three non-standard ones: the pipe |, optional chaining ?., and TypeScript’s non-null assertion !.
Not supported: all bitwise operators, object and array destructuring, the comma operator, and new.
No declarations. No let, const, function, arrow functions, or classes inside an expression. @let is the sanctioned way to name a value.
this and shadowing
Section titled “this and shadowing”Expressions evaluate against the component class, with this implied. A template variable with the same name as a class member shadows it, and this. disambiguates — which is what makes the signal-narrowing idiom work:
@let user = this.user();@if (user) { <p>{{ user.name }}</p>}Optional chaining changed in v22
Section titled “Optional chaining changed in v22”Before Angular 22, ?. in a template returned null when the left side was nullish, diverging from JavaScript’s undefined. Since v22, it matches standard JavaScript.
The ng update migration wraps affected expressions in $safeNavigationMigration(...) to preserve the old behaviour:
{{ $safeNavigationMigration(foo?.bar) }}That is a temporary migration aid only — not a real function, not callable from TypeScript, and possibly removed in a future version. Rewrite the expressions so they do not depend on the null-versus-undefined distinction, then delete the wrapper. Leaving them in place indefinitely is accumulating a debt with a deadline someone else will hit.
Bindings
Section titled “Bindings”Interpolation
Section titled “Interpolation”<p>{{ order().customer }}</p><p>Total: {{ order().total | currency }}</p>Always escaped. This is the safe default and should be the first thing you reach for.
Property bindings
Section titled “Property bindings”<img [src]="imageUrl()" [alt]="description()" /><order-row [order]="order()" [dense]="isCompact()" /><input [disabled]="isReadOnly()" />Square brackets bind a DOM property or a component/directive input. Property bindings are typed: the template type checker verifies the expression against the input’s declared type.
Attribute bindings
Section titled “Attribute bindings”<td [attr.colspan]="span()"></td><div [attr.data-testid]="id()"></div>Use attr. when there is no corresponding DOM property. colspan, data-*, and SVG attributes are the usual cases. Binding an attribute to null removes it, which is how you express a conditional attribute.
ARIA attributes bind directly — the compiler recognises the aria- prefix and compiles them as attribute bindings:
<button [aria-label]="actionLabel()">{{ actionLabel() }}</button><div [aria-expanded]="isOpen()"></div>Static ones are plain HTML: <button aria-label="Save document">. Binding to null removes the attribute.
Some ARIA relationships need element references rather than strings, and those are real property bindings on directive inputs:
<h2 #title>Attention</h2><p #description>Review your answers before continuing.</p>
<section role="dialog" [ariaLabelledByElements]="[title, description]"> <ng-content /></section>That is better than binding aria-labelledby to a string of ids, because the references stay correct as the template changes rather than depending on ids you maintain by hand.
Classes and styles
Section titled “Classes and styles”<div [class.active]="isActive()"></div><div [class]="{ active: isActive(), disabled: isDisabled() }"></div><div [class]="classString()"></div>
<div [style.width.px]="width()"></div><div [style.color]="hasError() ? 'red' : 'inherit'"></div><div [style]="{ width: width() + 'px' }"></div>The unit suffix (.px, .%, .em) is a small convenience that removes a lot of string concatenation.
Do not build an object literal inline — [class]="{ active: isActive() }" creates a new object every check, so a child never skips. Use [class.active] for single classes, or a computed for a set.
Event listeners
Section titled “Event listeners”<button (click)="save()">Save</button><input (input)="filter.set($any($event.target).value)" /><form (submit)="onSubmit($event)"></form>$event is the event object. Handlers are statements, not expressions, so assignment is allowed — but destructuring assignment is not.
Key modifiers
Section titled “Key modifiers”<input (keydown.enter)="submit()" /><input (keydown.escape)="cancel()" /><div (keydown.control.shift.p)="openPalette()"></div>Far more readable than if (event.key === 'Enter' && event.ctrlKey && event.shiftKey) in a handler, and self-documenting at the call site.
Global targets
Section titled “Global targets”<div (window:resize)="onResize()" (document:click)="onOutsideClick($event)"></div>document:, window: and body: are the supported prefixes. Angular removes these listeners on destroy, which is the main reason to use them over addEventListener.
Preventing defaults
Section titled “Preventing defaults”Return false from a handler, or call $event.preventDefault() explicitly. Prefer the explicit call — the return false shorthand is easy to miss and unclear about what it does.
Template variables
Section titled “Template variables”Template reference variables
Section titled “Template reference variables”<input #searchBox /><button (click)="search(searchBox.value)">Search</button>
<order-panel #panel="orderPanel" /><button (click)="panel.reset()">Reset</button>#name on a plain element gives the DOM element. #name="exportAsName" gives the directive instance — that is what #f="ngForm" is doing in a template-driven form, and forgetting the export is why #f sometimes turns out to be the <form> element.
Reference variables are visible in the template where they are declared, including inside @if/@for blocks in the same template, but not inside a separate <ng-template> unless passed in.
@let total = order().lines.reduce((sum, l) => sum + l.amount, 0);@let user = currentUser();
<p>{{ total | currency }}</p>@if (user) { <p>{{ user.name }}</p>}@let names a value, scoped to its block and everything below it. It is read-only — you cannot assign to it from a handler.
Two things it is genuinely good for: readability of long expressions, and narrowing a signal read so TypeScript can treat it as a variable (which is required for @switch exhaustiveness checks).
It is not memoisation — the expression re-evaluates on each check. Expensive derivations belong in a computed.
ng-container and ng-template
Section titled “ng-container and ng-template”<ng-container> groups elements without rendering a wrapper:
<ng-container *ngIf="isVisible"> <td>One</td> <td>Two</td></ng-container>Indispensable inside <table>, <select> and flex or grid layouts, where an extra <div> breaks the layout or produces invalid HTML — which, under hydration, is a real error rather than a cosmetic one.
<ng-template> declares a fragment that is not rendered until something renders it:
<ng-template #emptyState> <p>Nothing to show.</p></ng-template>
<ng-container *ngTemplateOutlet="emptyState" />With built-in control flow, most everyday ng-template use has disappeared. It remains the right tool for customisable slots — a table component letting consumers supply a cell renderer, for example:
<data-table [rows]="rows()"> <ng-template #cell let-row let-column="column"> <status-badge [status]="row[column]" /> </ng-template></data-table>let-row binds the implicit context value; let-column="column" binds a named one. Templates can also be rendered imperatively through ViewContainerRef and can be given their own injector — the mechanism behind most dialog and overlay libraries.
Template type checking
Section titled “Template type checking”Angular type-checks templates against the component class. strictTemplates in tsconfig.json turns this from advisory into genuinely strict:
"angularCompilerOptions": { "strictTemplates": true}With it on, input binding types are checked exactly, $event is typed per event, template reference variables get their real element types, and directive contexts are checked.
It is worth enabling on any codebase you intend to keep. The class of bug it catches — a string | null bound to an input declared string, a typo in an input name — is exactly the class that otherwise surfaces as a runtime error in production.
$any(...) is the escape hatch when the checker is wrong or a third-party type is inadequate. Treat each use as a small piece of debt.
Anti-patterns
Section titled “Anti-patterns”| Anti-pattern | Cost |
|---|---|
| Method calls in bindings | Re-executed on every check of the view |
| Object/array literals in bindings | New reference each check; children never skip |
| Complex logic in a template | Untestable, unreadable, re-evaluated constantly |
[innerHTML] where interpolation would do |
Relies entirely on the sanitizer |
| Deeply nested control flow | Extract a child component |
$any(...) to silence the type checker |
Discards the checking you enabled |
::ng-deep |
Deprecated; couples to internal structure — expose CSS custom properties |
ElementRef.nativeElement manipulation |
Breaks SSR and hydration; bypasses sanitization |
Wrapper <div> inside a table or grid |
Invalid HTML; breaks hydration — use <ng-container> |
$safeNavigationMigration left permanently |
A temporary aid that may be removed |
| Business logic in an event statement | Untestable; belongs in a method |
Related pages
Section titled “Related pages”- Control Flow:
@if,@for,@switchand@defer - Pipes
- Host Binding and Host Listening
- Content Queries and Content Projection
- Angular Security
- Templates basics