Sub topic 4
Attribute, Class and Style Bindings
Property binding writes a value to a DOM property. Some things you want to control are not plain DOM properties, though. Some HTML attributes have no matching property. A CSS class list is a set you toggle one entry at a time. Inline styles need units. Angular has three binding forms for these cases: attr., class. and style..
This chapter assumes you know HTML and the DOM, can write a standalone Angular component, and have read the previous chapter on property binding with [property]="expression".
Attributes and Properties Are Different Things
An HTML attribute is text written in the markup, such as colspan="2". The browser reads the attributes when it parses the page and uses them to set up DOM objects. A DOM property is a field on that JavaScript object, such as td.colSpan. The two often look alike, but they differ in several ways:
| Aspect | HTML attribute | DOM property |
|---|---|---|
| Where it lives | In the markup, read with `getAttribute()` | On the JavaScript element object |
| Value type | Always a string | Any type: boolean, number, object |
| Naming | Lowercase, often hyphenated (`aria-label`) | camelCase (`colSpan`, `tabIndex`) |
| After user interaction | Usually keeps its initial value (`value` on an input) | Holds the current state |
| Exists for | Every attribute in the markup | Only names the element's interface defines |
Angular's plain [name] syntax always targets a property. The compiler checks that name against a schema of known DOM properties. A few lowercase names, such as tabindex, readonly and for, are mapped to their camelCase properties for you. Most names are not mapped. Writing [colspan] therefore fails at compile time with "Can't bind to 'colspan' since it isn't a known property of 'td'". Binding [colSpan] works because colSpan is the real property name. Many attributes have no property at all, including aria-*, role in older browsers, data-*, and most SVG presentation attributes. For those, you need an attribute binding.
Attribute Binding with attr.
An attribute binding has the form [attr.name]="expression". Angular calls setAttribute(name, String(value)) on the element. If the value is null or undefined, Angular calls removeAttribute(name) instead.
import { Component } from '@angular/core';
@Component({
selector: 'app-table-cell',
template: `
<table>
<tr><td [attr.colspan]="span">Total</td></tr>
</table>
<button
[attr.aria-label]="label"
[attr.aria-expanded]="expanded"
[attr.data-test-id]="testId"
(click)="expanded = !expanded">
☰
</button>
`,
})
export class TableCellComponent {
span = 2;
label = 'Open menu';
expanded = false;
testId: string | null = null; // null: attribute is not rendered
}In this example, aria-expanded renders as the string "false" or "true". That is what screen readers expect, because ARIA states are string tokens and not HTML boolean attributes.
Gotcha: false Is Not Removal
Boolean HTML attributes such as hidden or disabled count as "on" whenever they are present, whatever their value. [attr.disabled]="false" writes disabled="false", and that still disables the element. To remove the attribute, bind null:
import { Component } from '@angular/core';
@Component({
selector: 'app-toggle',
template: `
<!-- Wrong: renders disabled="false", button is still disabled -->
<button [attr.disabled]="locked">A</button>
<!-- Right: attribute is removed when not locked -->
<button [attr.disabled]="locked ? '' : null">B</button>
<!-- Usually best: the DOM property takes a real boolean -->
<button [disabled]="locked">C</button>
`,
})
export class ToggleComponent {
locked = false;
}SVG and Custom Elements
SVG elements expose many attributes as animated objects (SVGAnimatedLength) and not as plain writable properties. [attr.cx]="x" is the reliable way to bind SVG geometry. Custom elements (web components) usually accept both forms, but only properties can carry objects. Use attr. for those elements only when the element's documentation says it reads an attribute.
Class Binding
Toggling a Single Class
[class.name]="condition" adds the class when the expression is truthy and removes it when the value is falsy. Angular adds and removes only that one class. Other classes on the element are not touched.
import { Component } from '@angular/core';
@Component({
selector: 'app-tab',
template: `
<div class="tab" [class.active]="isActive" [class.has-error]="errors > 0">
Settings
</div>
`,
styles: [`.active { font-weight: bold; } .has-error { color: crimson; }`],
})
export class TabComponent {
isActive = true;
errors = 0;
}The static class="tab" stays on the element. Angular merges static classes with bound ones and does not overwrite them.
Binding Many Classes at Once
[class]="expression" accepts three shapes:
| Expression type | Example | Result |
|---|---|---|
| String | `'card large'` | Adds every space-separated name |
| Array | `['card', 'large']` | Adds every entry |
| Object | `{ card: true, large: isLarge }` | Adds keys whose values are truthy |
When the value changes, Angular adds the new classes and removes the classes that the previous value added. Static classes and classes added by [class.x] bindings are left alone.
Gotcha: Mutating an Object or Array Does Nothing
For object, array, Map and Set expressions, Angular compares by identity. If you change a key in place, Angular sees the same reference and skips the update.
import { Component } from '@angular/core';
@Component({
selector: 'app-card',
template: `
<div [class]="classes">Card</div>
<button (click)="brokenToggle()">Broken</button>
<button (click)="toggle()">Works</button>
`,
styles: [`.large { font-size: 2rem; }`],
})
export class CardComponent {
classes: Record<string, boolean> = { card: true, large: false };
brokenToggle() {
this.classes.large = !this.classes.large; // same object: no DOM update
}
toggle() {
this.classes = { ...this.classes, large: !this.classes.large }; // new object
}
}The same rule applies to [style] objects. Using a computed() signal that returns a fresh object, or a getter that builds a new literal, avoids this problem.
Style Binding
Single Styles and Units
[style.property]="value" sets one inline style. You can write the property name in dash-case (background-color) or camelCase (backgroundColor). A third segment adds a unit, so [style.width.px]="240" sets width: 240px. Any CSS unit works, including px, em, rem, %, vh and s.
import { Component } from '@angular/core';
@Component({
selector: 'app-progress',
template: `
<div class="track">
<div
class="bar"
[style.width.%]="percent"
[style.background-color]="percent < 30 ? 'crimson' : 'seagreen'"
[style.--bar-radius]="radius">
</div>
</div>
`,
styles: [`
.track { width: 300px; background: #eee; }
.bar { height: 12px; border-radius: var(--bar-radius, 0); }
`],
})
export class ProgressComponent {
percent = 65;
radius = '6px';
}[style.--bar-radius] sets a CSS custom property. This lets CSS keep control of the visual design, while the component supplies only the data.
Binding null or undefined removes the style, and the stylesheet value applies again. A number without a unit suffix is written as given. For width, a bare 240 is invalid CSS, so the browser ignores it without any error. If a style looks like it is not applying, check this first.
Binding Many Styles at Once
[style] accepts a string ('width: 100px; color: red') or an object ({ width: '100px', 'font-size.px': 14 }). Object keys can include the unit suffix. Angular diffs the object against the previous one and removes styles whose keys have disappeared. The identity rule from the class section applies here as well.
How Bindings Combine: Precedence
One element can get the same class or style from several places: a static attribute, a template binding, and host bindings on directives or the component. Angular resolves conflicts with a fixed order, from highest priority to lowest:
- Template bindings on the element, with specific bindings (
[class.foo],[style.width]) ahead of map bindings ([class],[style]). - Directive host bindings, in the same specific-then-map order.
- Component host bindings.
- Static
classandstyleattributes in the template.
If a higher-priority binding resolves to null or undefined, it steps aside and the next one applies. [style.width]="null" therefore lets a directive's host width or the static style take effect again. This rule is what lets a reusable directive set default styling that a template can override.
ngClass and ngStyle
NgClass and NgStyle from @angular/common do the same jobs as [class] and [style]. They also accept keys with several class names, such as { 'btn btn-primary': ok }. They still work, but Angular's documentation recommends the built-in bindings. The built-in bindings need no import, take part in the precedence rules above, and cost less at runtime. Expect to see ngClass in older code. Convert it when you are already editing that code.
Quick Reference
| Goal | Syntax | Null or undefined does |
|---|---|---|
| Attribute with no DOM property | `[attr.aria-label]="x"` | Removes the attribute |
| Toggle one class | `[class.active]="flag"` | Removes the class |
| Set of classes | `[class]="'a b'"`, `[class]="['a']"`, `[class]="{a: flag}"` | Removes the classes it added |
| One style with unit | `[style.height.rem]="h"` | Removes the style |
| CSS custom property | `[style.--gap]="'8px'"` | Removes the variable |
| Many styles | `[style]="{ color: c }"` | Removes the styles it added |
Exercise
A template contains <td [colspan]="cols"> and fails to compile. A teammate fixes it by writing [attr.colspan]="cols", and another proposes [colSpan]="cols". Which fixes work, and why did the original fail?
Show answer
Both fixes work. [attr.colspan] calls setAttribute('colspan', ...) directly. [colSpan] targets the real DOM property, which is camelCase. The original failed because plain bindings target properties, and Angular's schema does not map the lowercase name colspan to the colSpan property, so the compiler reports that colspan is not a known property of td.
Exercise
A component has state = { open: false } and the template <div [class]="state">. A click handler runs this.state.open = true, but the open class never appears. Explain the cause and give two fixes.
Show answer
For object expressions, [class] compares by identity. Mutating a key keeps the same reference, so Angular sees no change. Fix 1: assign a new object, this.state = { ...this.state, open: true }. Fix 2: drop the object and use [class.open]="isOpen" with a boolean field, or with a signal read as isOpen().
Exercise
You want an <input> to be read-only only while saving is true. Why is [attr.readonly]="saving" wrong, and what should you write instead?
Show answer
When saving is false, the attribute binding writes readonly="false". The attribute is still present, so the input stays read-only. Write [readOnly]="saving" to use the boolean DOM property (Angular also maps the lowercase [readonly] to it), or write [attr.readonly]="saving ? '' : null" so the attribute is removed when saving is false.