Sub topic 10
Attribute, Class, and Style Bindings
Property binding, covered earlier, writes to DOM properties. Some things you want to control are not properties: ARIA attributes, colspan, data-* values, CSS classes, and individual style declarations. Angular has dedicated binding forms for each of these. This chapter covers how they work, how they combine with static markup, and where they surprise people.
This chapter assumes you know property binding ([prop]="expr"), reading signals in templates, and input() from the inputs and outputs chapter.
Why attributes need their own binding
HTML attributes and DOM properties are different things. The parser reads attributes to initialize properties, and after that the two can diverge. Many attributes also have no matching property. aria-label, colspan (the property is colSpan), role, and every data-* attribute are examples, and SVG attributes such as viewBox are another. If you write [aria-label]="x", Angular compiles it as a property binding, finds no aria-label property on the element, and reports an error like "Can't bind to 'aria-label' since it isn't a known property".
The attr. prefix tells Angular to call setAttribute instead:
<button [attr.aria-label]="closeLabel()">×</button>
<td [attr.colspan]="span()">Total</td>
<div [attr.data-row-id]="row().id"></div>When the expression evaluates to null or undefined, Angular calls removeAttribute. Use that to make an attribute conditional:
<input [attr.aria-describedby]="hasError() ? 'email-error' : null" />Attribute values are always strings. Angular converts numbers and booleans with String(), so [attr.aria-expanded]="open()" writes "true" or "false", which is what ARIA expects.
Class bindings
Angular supports two forms of class binding.
The single-class form toggles one class based on a truthy expression:
<li [class.active]="selected()">...</li>The multi-class form takes a string, an array, or an object:
<div [class]="'card elevated'"></div>
<div [class]="['card', theme()]"></div>
<div [class]="{ card: true, elevated: raised(), compact: dense() }"></div>Both forms merge with a static class attribute on the same element. They do not replace it. Given class="bar" plus [class]="tone()", the element keeps bar and gains whatever tone() returns. When tone() changes, Angular removes only the classes the binding added before.
The reference-equality gotcha
For array and object values, Angular checks whether the reference changed. It does not compare contents. If you mutate an object in place, the DOM keeps showing the old classes:
// Broken: same object reference, no update
this.classes.active = true;Create a new object instead. With signals, the usual pattern is a computed() that returns a fresh object every time a dependency changes:
classes = computed(() => ({ active: this.selected(), disabled: this.locked() }));The older NgClass directive compares contents, so it hides this mistake. It still works, but the built-in [class] binding needs no import and costs less, and Angular's documentation recommends it.
Style bindings
Style bindings follow the same pattern. The single-property form sets one CSS property:
<div [style.color]="accent()"></div>
<div [style.background-color]="bg()"></div>
<div [style.backgroundColor]="bg()"></div>You can write the property name in dash-case or camelCase. A unit suffix appends the unit for you, so you can bind a plain number:
<div [style.width.px]="width()"></div>
<div [style.height.%]="percent()"></div>
<div [style.margin-top.rem]="gap()"></div>CSS custom properties work too, which lets the stylesheet own the visual rules while the template supplies values:
<div [style.--accent]="brandColor()"></div>The multi-property form accepts a string or an object:
<div [style]="'display: grid; gap: 8px'"></div>
<div [style]="{ display: 'grid', 'grid-template-columns': cols() }"></div>Object values follow the same reference rule as [class]. Mutating a style object in place will not update the DOM. As with classes, null or undefined removes the property.
A worked example
The progress bar below uses every form from this chapter. ARIA state goes through attribute bindings, state classes through class bindings, and geometry and theme color through style bindings.
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-progress',
template: `
<div
class="track"
role="progressbar"
aria-valuemin="0"
aria-valuemax="100"
[attr.aria-valuenow]="clamped()"
[attr.aria-label]="label() || null">
<div
class="bar"
[class]="toneClasses()"
[class.complete]="clamped() === 100"
[style.width.%]="clamped()"
[style.--bar-color]="color()"></div>
</div>
`,
styles: `
.track { height: 8px; background: #eee; border-radius: 4px; overflow: hidden; }
.bar { height: 100%; background: var(--bar-color, steelblue); transition: width 200ms; }
.bar.striped { background-image: repeating-linear-gradient(45deg, #fff3 0 6px, transparent 6px 12px); }
.bar.complete { background: seagreen; }
`
})
export class ProgressComponent {
value = input(0);
label = input('');
color = input<string | null>(null);
striped = input(false);
clamped = computed(() => Math.min(100, Math.max(0, this.value())));
toneClasses = computed(() => ({ striped: this.striped() && this.clamped() < 100 }));
}A parent uses it like this:
<app-progress [value]="uploaded()" label="Upload progress" color="#7b4fd6" [striped]="true" />Note the details. When label() is empty, || null removes aria-label instead of writing an empty one. color defaults to null, so no --bar-color declaration is written and the CSS fallback applies. toneClasses comes from computed, so the class object is a new reference whenever its inputs change.
Precedence when bindings collide
One element can get the same class or style from several places: a static attribute, [class], [class.x], and host bindings from directives or the component itself (covered in a later chapter). Angular resolves the conflict with fixed rules:
- A more specific binding beats a less specific one.
[class.x]and[style.width]beat[class]and[style], which beat staticclassandstyleattributes. - Template bindings beat directive host bindings, which beat component host bindings.
| Source | Example | Priority |
|---|---|---|
| Template single binding | `[style.width.px]="w"` | Highest |
| Template map binding | `[style]="{ width: '50px' }"` | |
| Static template attribute | `style="width: 10px"` | |
| Directive host bindings | `host: { '[style.width]': ... }` | |
| Component host bindings | on the component's own host | Lowest |
When a higher-priority binding becomes null or undefined, the next one down takes effect again. That lets you write a style override that applies only some of the time.
Common errors
- Using
[class]and expecting it to replace static classes. It merges with them. To drop a static class, make it conditional with[class.x]. - Mutating objects or arrays bound to
[class]or[style]. Return new references, ideally fromcomputed(). - Forgetting the unit.
[style.width]="120"is ignored because120is not valid CSS. Use[style.width.px]. - Binding
aria-*as a property. Use[attr.aria-*]. - Building inline style strings by concatenation. This is fragile and hard to read. Prefer individual style bindings or CSS custom properties with rules in the stylesheet.
Exercise
A template has <div class="panel" [class]="extra()"> and extra is a signal holding 'wide'. You call extra.set('tall'). Which classes are on the element afterwards, and why?
Show answer
panel tall. The [class] binding merges with the static class attribute. When its value changes, Angular removes only the classes that binding added earlier (wide) and adds the new ones (tall), so panel stays.
Exercise
A component has flags = { error: false } and the template binds [class]="flags". A method runs this.flags.error = true, but the error class never appears. Fix it using signals.
Show answer
Angular checks object bindings by reference, so changing a property in place does not update the DOM. Store the state in a signal and derive a new object: hasError = signal(false); flags = computed(() => ({ error: this.hasError() }));. Bind [class]="flags()" and call this.hasError.set(true). A simpler option is [class.error]="hasError()".
Exercise
Write a binding that sets aria-expanded to "true" or "false" from an open signal, and one that adds aria-controls="menu" only while the menu is open.
Show answer
[attr.aria-expanded]="open()" writes the boolean converted to a string. [attr.aria-controls]="open() ? 'menu' : null" removes the attribute when the expression is null.