Sub topic 5
Binding to DOM Properties
This chapter assumes you have read the earlier chapters on component anatomy, interpolation, and reading signals in templates. It also assumes you know the basics of the DOM: an <input> element in the page is a JavaScript object with properties such as value and disabled.
Interpolation puts text into the page. Property binding is more general. It sets any property of a DOM element from a template expression and keeps that property up to date while the value changes.
The Syntax and the Data Flow
Wrap a property name in square brackets and give it an expression:
<img [src]="avatarUrl()" [alt]="userName()" />
<button [disabled]="isSaving()">Save</button>Angular evaluates the right-hand side in the context of the component class. It then assigns the result to the element's DOM property, which works like running button.disabled = isSaving() in plain JavaScript. During each change detection pass, Angular evaluates the expression again and writes to the DOM only when the result is different from the previous one.
Data moves in one direction only, from the class to the DOM. If the user types into an <input> whose value is bound, the class does not change. You handle that direction with event binding and two-way binding in later chapters.
A Complete Example
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-profile-editor',
template: `
<img [src]="avatarUrl()" [alt]="'Avatar of ' + name()" width="64" height="64" />
<input [value]="name()" [placeholder]="placeholder" />
<p [hidden]="!showHint()">Names must be at least 3 characters.</p>
<button [disabled]="name().length < 3 || saving()" (click)="save()">
{{ saving() ? 'Saving…' : 'Save' }}
</button>
`
})
export class ProfileEditorComponent {
name = signal('Ada');
saving = signal(false);
showHint = signal(true);
placeholder = 'Your name';
avatarUrl = signal('https://example.com/avatars/ada.png');
save() {
this.saving.set(true);
setTimeout(() => this.saving.set(false), 1000);
}
}Look at what each binding does:
[src]and[alt]set string properties. Thealtexpression joins a string literal and a signal.[value]sets the input's current value, not its initialvalueattribute. This difference matters, as the next section shows.[hidden]takes a real boolean.[disabled]takes the result of a boolean expression.[placeholder]reads a plain field. A field is fine for a value that never changes. Signals become important when values change and when you use OnPush change detection, which a later chapter covers.
Attributes Are Not Properties
HTML attributes and DOM properties are separate things, and most property binding mistakes come from mixing them up.
- An attribute is written in the HTML source. It is always a string, and it mostly sets the starting state.
- A property lives on the DOM object. It can be any type, and it holds the current state.
Some attributes map to a property with the same name, such as id and src. Others map to a property with a different name or type. Some have no matching property at all.
| HTML attribute | DOM property | Note |
|---|---|---|
| `value` | `value` | The attribute is the initial value. The property is the live value. |
| `disabled` | `disabled` | The attribute is present or absent. The property is a boolean. |
| `colspan` | `colSpan` | The names differ in case. Bind `[colSpan]`. |
| `for` | `htmlFor` | `for` is a reserved word in JavaScript. |
| `class` | `className` | Angular has dedicated class bindings, covered in a later chapter. |
| `aria-label` | `ariaLabel` (not in every browser) | Use `[attr.aria-label]` instead. |
| `data-id` | `dataset.id` | Use `[attr.data-id]` instead. |
In a property binding, the name inside the brackets refers to the property. That is why [colspan]="2" fails, while [colSpan]="2" works.
Common Errors
A String Literal Versus an Expression
Without brackets, Angular treats the right-hand side as a static string. With brackets, it treats it as an expression.
<input placeholder="userName" /> <!-- the literal text "userName" -->
<input [placeholder]="userName" /> <!-- the value of the userName field -->
<input [placeholder]="'userName'" /> <!-- a string literal; brackets add nothing here -->If you write [placeholder]="Search" by mistake, Angular looks for a class member called Search and finds nothing. In strict template mode, which new projects use by default, that is a compile error.
The "false" String Trap
<button disabled="false">Still disabled</button>
<button [disabled]="false">Enabled</button>The first button is disabled. The attribute is present, and for boolean attributes only presence counts, so the string "false" makes no difference. The second button assigns the boolean false to the property, so the button is enabled.
Interpolation Inside Attributes
<img src="{{ url() }}"> is shorthand for a property binding that always produces a string, because Angular converts the result to a string. Use it only when you are building text, as in title="Hello {{ name() }}". For booleans, numbers, objects, or a single value, use brackets. Interpolation would turn false into "false".
Side Effects and Expensive Expressions
Angular may evaluate a binding expression on every change detection pass. In development mode it runs an extra check to confirm that the value has not changed between passes. Keep binding expressions cheap and free of side effects. Do not call a method that changes state or builds a new array on each call. Use a computed() signal for derived values.
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-cart-button',
template: `<button [disabled]="isEmpty()">Checkout</button>`
})
export class CartButtonComponent {
items = signal<string[]>([]);
isEmpty = computed(() => this.items().length === 0);
}Binding to innerHTML and Security
You can bind HTML markup with [innerHTML]. Angular sanitizes the value first. It removes dangerous content such as <script> elements and onclick handlers, and in development mode it logs a console warning when it removes something.
import { Component } from '@angular/core';
@Component({
selector: 'app-note',
template: `<div [innerHTML]="html"></div>`
})
export class NoteComponent {
html = '<b>Bold</b><img src="x" onerror="alert(1)">';
}In this example, Angular renders the bold text and the image but removes the onerror handler. DomSanitizer.bypassSecurityTrustHtml turns sanitization off. Use it only for content you fully control, because using it on user input opens your app to cross-site scripting (XSS).
Edge Cases Worth Knowing
- Property names are case-sensitive and follow the DOM spelling exactly:
[tabIndex],[readOnly],[maxLength],[colSpan]. nullandundefinedare passed through as they are. Setting[src]tonullcan make some browsers request a URL that contains the text "null". Guard the binding with@if, or use[attr.src], which removes the attribute when the value isnull.[value]on<select>works only after the<option>elements exist. Because Angular renders options inside@for, a value bound too early may not take effect. Forms APIs handle this case better.- Component inputs use the same bracket syntax.
[title]="..."on<app-todo-item>sets an input instead of a DOM property. The inputs chapter explains how Angular decides which one you mean.
Exercise
A template contains <td colspan="{{ span() }}"> and <button disabled="{{ locked() }}">, where locked() returns false. Explain what happens in each case and rewrite both lines correctly.
Show answer
colspan="{{ span() }}" is an interpolated property binding to colspan. That is not a DOM property (the property is colSpan), so compilation fails with NG0303. disabled="{{ locked() }}" binds the string "false" to the disabled property, and a non-empty string is truthy, so the button stays disabled. Correct versions: <td [colSpan]="span()"> and <button [disabled]="locked()">.
Exercise
Why does typing in <input [value]="name()"> not update the name signal, and why might the typed text be overwritten later?
Show answer
Property binding is one-way, from the class to the DOM. Typing changes the element's value property, but nothing writes that value back to the signal. When name changes later, Angular sees a new value and assigns it to the property, which replaces what the user typed. To keep them in sync, add an event binding or use two-way binding.