Sub topic 4
Attribute, Class and Style Bindings
This chapter assumes you know property binding from the previous chapter, the difference between HTML markup and the live DOM, and basic CSS. Property binding writes to DOM properties. Sometimes no property exists for the thing you want to set, and sometimes you only want to toggle one CSS class or one style without replacing the whole value. Angular has three prefixed binding forms for these cases: attr., class. and style..
Attributes Versus Properties
HTML attributes set an element's starting state in the markup. DOM properties are the live values on the JavaScript object. Many attributes map to a property with the same name, such as src, alt and disabled. Some don't:
colspanmaps to the propertycolSpan, so[colspan]fails because no property has that exact name.- ARIA attributes such as
aria-label, and customdata-*attributes, are not ordinary element properties you can rely on. - SVG elements expose many attributes only as attributes.
If you bind to a property that does not exist, the compiler reports an error such as "Can't bind to 'colspan' since it isn't a known property of 'td'". The fix is an attribute binding.
Attribute Binding with `attr.`
An attribute binding calls setAttribute on the element. If the value is null or undefined, Angular removes the attribute entirely.
import { Component } from '@angular/core';
@Component({
selector: 'app-table-cell',
template: `
<table><tr><td [attr.colspan]="span">Total</td></tr></table>
<div [class.active]="isActive" [style.width.px]="width">Panel</div>
`,
})
export class TableCellComponent {
span = 2;
isActive = true;
width = 240;
}ARIA and data attributes work the same way:
import { Component } from '@angular/core';
@Component({
selector: 'app-icon-button',
template: `
<button [attr.aria-label]="label" [attr.data-test-id]="testId">✕</button>
`,
})
export class IconButtonComponent {
label = 'Close dialog';
testId: string | null = null; // null: attribute is not rendered
}Class Bindings
[class.name]="condition" adds the class name when the expression is truthy and removes it when it is falsy. Other classes on the element stay as they are, including static ones in class="...".
To manage several classes at once, bind to [class]. It accepts three forms:
| Value form | Example | Result |
|---|---|---|
| String | `'card selected'` | Adds both classes |
| Array | `['card', 'selected']` | Adds both classes |
| Object | `{ card: true, selected: isSel }` | Adds keys whose values are truthy |
Style Bindings
[style.prop] sets a single CSS property. You can write the property name in dash-case (background-color) or camelCase (backgroundColor). A unit suffix appends the unit to a numeric value:
import { Component } from '@angular/core';
@Component({
selector: 'app-progress',
template: `
<div class="bar"
[style.width.%]="percent"
[style.background-color]="percent < 50 ? 'orange' : 'green'"
[style]="{ height: '8px', borderRadius: '4px' }">
</div>
`,
})
export class ProgressComponent {
percent = 65;
}If you leave out the unit, the value must already contain one: [style.width]="'240px'" works, but [style.width]="240" gives the browser an invalid value, and it ignores it. Binding null removes the style.
When [style] and [style.width] both set the same property, the more specific single-property binding wins. Class bindings follow the same rule.
Choosing a Binding
Common Errors
- Writing
[colspan]or[aria-label]without theattr.prefix. - Expecting
falseto remove an attribute.[attr.x]="false"rendersx="false". Usenullto remove it. - Forgetting the unit on a numeric style value.
- Mutating a bound class or style object in place and expecting the view to update.
Exercise
A <div> must have the class error only when hasError is true, a data-row attribute equal to rowIndex that disappears when rowIndex is null, and a height of rowHeight pixels, where rowHeight is a number. Write the bindings.
Show answer
<div [class.error]="hasError" [attr.data-row]="rowIndex" [style.height.px]="rowHeight"></div>. The attr. binding removes the attribute when rowIndex is null, and the .px suffix adds the unit to the numeric height.
Exercise
Why does [attr.hidden]="isHidden" keep the element hidden when isHidden is false?
Show answer
Attribute binding renders hidden="false", and hidden is a boolean attribute, so its presence alone hides the element. Bind [attr.hidden]="isHidden ? '' : null" instead, or use the property binding [hidden]="isHidden".