Sub topic 3
Binding to DOM Properties
This chapter assumes you know HTML and the DOM, TypeScript classes, and how to generate and run a component with the Angular CLI. It also assumes you have read the earlier chapters on template expressions and interpolation.
Interpolation puts a value into text. Most UI state is not text, though. Whether a button is disabled, which image an <img> shows, and what an <input> currently holds are all properties of DOM objects. Property binding is Angular's way of writing a component value straight into one of those properties.
The Syntax and What It Does
A property binding wraps a target name in square brackets and assigns it a template expression:
import { Component } from '@angular/core';
@Component({
selector: 'app-profile',
template: `
<h2>{{ name }}</h2>
<img [src]="avatarUrl" [alt]="name">
<button [disabled]="!canEdit">Edit</button>
`,
})
export class ProfileComponent {
name = 'Ada';
avatarUrl = '/assets/ada.png';
canEdit = false;
}Read [disabled]="!canEdit" as an instruction: "evaluate !canEdit against the component, then assign the result to the button element's disabled property." It compiles to something close to buttonElement.disabled = !component.canEdit, with Angular's renderer doing the assignment.
Data flows one way only, from component to DOM. If something else changes button.disabled later, for example a browser extension or your own document.querySelector code, the component's canEdit field does not change. Angular will overwrite the DOM value the next time the expression's result changes.
Properties Are Not Attributes
This is the most important idea in the chapter. HTML attributes and DOM properties are different things.
- An attribute is written in HTML markup, such as
<input value="hello">. Attributes are always strings, and they set up an element's initial state. - A property lives on the JavaScript object the browser creates for the element, such as
inputElement.value. Properties can hold any type and reflect the current state.
The two are often linked, but not always in the way you expect. The value attribute of an <input> sets its starting value. Once the user types, input.value (the property) changes while getAttribute('value') still returns "hello". Some attributes have no property at all, such as colspan's cousins in ARIA or data-*. Some properties have no attribute, such as textContent.
Angular property binding targets properties. That one fact explains most of the surprises in this chapter.
| HTML attribute | DOM property | Type of the property |
|---|---|---|
| `class` | `className` | string |
| `for` | `htmlFor` | string |
| `readonly` | `readOnly` | boolean |
| `tabindex` | `tabIndex` | number |
| `disabled` | `disabled` | boolean |
| `value` (on input) | `value` | string, current value |
| none | `textContent` | string |
| `colspan` | `colSpan` | number |
Angular's DOM schema maps a few common attribute names to their property names for you: class, for, formaction, innerHtml, readonly and tabindex. So [readonly]="locked" and [readOnly]="locked" both work. For any other name, write the real property name, such as [colSpan]. If you need an attribute that has no property at all, you need an attribute binding, which the next chapter covers along with class and style bindings.
Values Keep Their Types
Property binding passes the expression's actual value without turning it into a string. That matters for booleans and numbers.
import { Component } from '@angular/core';
@Component({
selector: 'app-quantity',
template: `
<label for="qty">Quantity</label>
<input
id="qty"
type="number"
[value]="quantity"
[min]="minimum"
[max]="maximum"
[readOnly]="locked"
[tabIndex]="locked ? -1 : 0">
<button
[disabled]="locked || quantity >= maximum"
[title]="'Maximum is ' + maximum">
Add one
</button>
<button (click)="locked = !locked">Toggle lock</button>
<p [hidden]="!locked">This order is locked.</p>
`,
})
export class QuantityComponent {
quantity = 3;
minimum = 1;
maximum = 10;
locked = false;
}Here [disabled] receives a real true or false, [tabIndex] receives a number, and [hidden] receives a boolean. The browser converts values where the property's type requires it. input.min is a string property, so 1 becomes "1". You don't have to do that conversion yourself.
The (click) binding on the toggle button is event binding, which a later chapter covers. Here it only lets you see the bindings update.
Interpolation in Property Position
You can also write a property binding with interpolation inside a plain attribute:
import { Component } from '@angular/core';
@Component({
selector: 'app-avatar',
template: `
<img src="{{ baseUrl }}/{{ userId }}.png" alt="Avatar for {{ userName }}">
`,
})
export class AvatarComponent {
baseUrl = '/assets/avatars';
userId = 42;
userName = 'Ada';
}Angular compiles src="{{ ... }}" into a property binding on src. The difference is that interpolation always produces a string. That is fine for src, alt and title, and often easier to read when you are joining text. It is wrong for non-string properties:
import { Component } from '@angular/core';
@Component({
selector: 'app-pitfall',
template: `
<!-- Disabled: the property receives the string "false", which is truthy -->
<button disabled="{{ isDisabled }}">Interpolated</button>
<!-- Enabled: the property receives the boolean false -->
<button [disabled]="isDisabled">Bound</button>
`,
})
export class PitfallComponent {
isDisabled = false;
}Common Errors
Forgetting the brackets
Without brackets, the right-hand side is a literal string, not an expression:
import { Component } from '@angular/core';
@Component({
selector: 'app-brackets',
template: `
<img src="avatarUrl" alt="wrong"> <!-- requests a file named "avatarUrl" -->
<img [src]="avatarUrl" alt="right"> <!-- requests /assets/ada.png -->
<img [src]="'/assets/fallback.png'" alt="literal in a binding">
`,
})
export class BracketsComponent {
avatarUrl = '/assets/ada.png';
}The third line is legal but adds nothing. If the value never changes, a plain attribute (src="/assets/fallback.png") is simpler and costs nothing at runtime.
Binding to a property that does not exist
NG8002: Can't bind to 'colspan' since it isn't a known property of 'td'.This compile-time error means the name you used does not exist on that element, and no directive on the element declares an input with that name. Common causes:
- You used an attribute name that has no matching property. The fix for
colspanis[colSpan]or[attr.colspan]. - You misspelled a property name or got its case wrong, for example
[innerHtml]on a non-mapped name or[tabindex]on an older version. - You meant to bind to a child component's input, but you did not import that component into the parent's
importsarray. - The element is a Web Component that Angular cannot inspect. Add
CUSTOM_ELEMENTS_SCHEMAto the component'sschemasonly in that case, because the schema switches off this check for unknown elements.
Setting null or undefined
Angular assigns the value as it is. For many string properties, the DOM converts null to the text "null". [src]="user.photo" with a missing photo will request a URL ending in null. Give the expression a fallback, such as [src]="user.photo ?? '/assets/placeholder.png'", or use @if to skip rendering the element.
Expressions with side effects
Angular may evaluate a binding expression many times. In development mode it also checks a second time to confirm the value has stopped changing. A binding such as [title]="nextId()", which returns a new value on every call, triggers ExpressionChangedAfterItHasBeenCheckedError (NG0100). Keep binding expressions pure and cheap: read fields, call getters that only compute, and leave the work to methods that event handlers call.
How Angular Decides Where the Value Goes
For [foo]="expr" on an element, the compiler resolves the target in this order:
- If a component or directive on the element declares an input named
foo, the value goes to that input. This is how parents pass data to children, which a later chapter covers. - Otherwise, if the DOM schema says the element has a property
foo, after applying the attribute-to-property name map, the value goes to that DOM property. - Otherwise, compilation fails with NG8002.
At runtime, Angular stores each binding's previous value. During change detection it re-evaluates the expression and compares the new result with the stored one by identity. It writes to the DOM only when the result differs. This has two consequences:
- Repeated checks are cheap, because unchanged bindings never touch the DOM.
- If you mutate an object in place and bind that object to a child input, the reference stays the same, so Angular sees no change for that binding. Bindings to primitive values, such as
[title]="user.name", still update, because the primitive result itself changed.
The chapter on change detection explains when these checks run.
Security Note on Content Properties
Some properties accept markup or URLs: innerHTML, src, href. Angular sanitizes values bound to these properties. For example, [innerHTML]="html" strips <script> tags and dangerous attributes, and a javascript: URL in [href] gets neutralized. Prefer [textContent] or interpolation when you only need text. The final chapter covers sanitization in full.
Exercise
A teammate writes <input type="checkbox" checked="{{ agreed }}"> with agreed = false, and the box renders checked. Explain why, and give the corrected binding.
Show answer
Interpolation always produces a string, so the checked property receives "false". A non-empty string is truthy, so the box is checked. Use property binding so the boolean passes through unchanged: <input type="checkbox" [checked]="agreed">.
Exercise
The template <td [colspan]="span"> fails with NG8002. Give two fixes and say how they differ.
Show answer
Use [colSpan]="span" to bind the real DOM property (a number), or [attr.colspan]="span" to set the HTML attribute. Both render the same cell. The property binding writes the live DOM property, while the attribute binding calls setAttribute and can remove the attribute when the value is null.
Exercise
A user types "7" into <input [value]="qty">, where qty = 3 and no event binding exists. What is qty now, what does the input show, and when would the input go back to "3"?
Show answer
qty is still 3, because property binding only flows from component to DOM. The input shows "7". Angular writes to the input only when the expression's result changes, so it stays at "7" until qty changes to a value other than 3. Setting qty back to 3 would not count as a change.