Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 74 ยท Templates and Data Binding

Property, Attribute, Class and Style Binding

Learn Angular's square-bracket bindings - [property], [attr.x], [class.x] and [style.x] - how properties differ from attributes, and how innerHTML is sanitized.

Interpolation with {{ }} puts text on the page. Most of the time, though, you want to control the elements themselves: disable a button, set an image source, add a CSS class, change a width. In Angular you do that with square brackets: [disabled]="isBusy()". The brackets say "evaluate the expression on the right and push the result into the target on the left, every time it changes."

This lesson covers the four binding targets (element properties, HTML attributes, CSS classes and inline styles), explains the difference between a property and an attribute (the single most useful idea here), and shows how Angular protects you when you bind HTML. You should know interpolation and template expressions first.

Angular itself needs its compiler and CLI, which this site cannot run. The typescript and html blocks marked as Angular are real Angular code you read. The <TryIt> examples are stand-ins: small plain TypeScript or JavaScript programs that re-create the idea so you can run it and experiment.

Property binding

A property binding writes to a DOM property of an element, a component input or a directive input:

HTML
<button type="button" [disabled]="isSaving()">Save</button>
<img [src]="user().avatarUrl" [alt]="user().name" width="48" height="48" />
<app-rating [value]="score()" />

When isSaving() changes from false to true, Angular sets button.disabled = true. It does not rebuild the button, and it does not touch the DOM at all if the value is unchanged. The last line targets an input() of a component (you will build those in Inputs and Outputs); the syntax is identical for a native element and a component.

A few details worth knowing:

  • The right-hand side is a template expression: no assignments, no new, no chained statements.
  • Property names are the DOM names, in camelCase. The HTML attribute readonly is the DOM property readOnly, tabindex is tabIndex, class is className and for is htmlFor. Angular maps a few of these for you, but when in doubt, use the DOM name.
  • Binding a string constant needs no brackets: <img src="logo.svg"> is plain HTML. Use brackets when the value comes from your component.
  • Interpolation is just property binding in disguise: <p title="Hi {{ name() }}"> is <p [title]="'Hi ' + name()">, and {{ }} in element content sets textContent.

Properties versus attributes

HTML attributes are what you write in markup. DOM properties are what JavaScript sees on the element object. The browser reads the attributes once, when it parses the tag, to set the initial properties. After that they can drift apart.

The classic example is the <input> element. The value attribute is the starting text; the value property is the current text, including whatever the user typed. A checkbox's checked attribute is its default state; its checked property is the live state. Other attributes have no property at all (aria-label, colspan on some elements, data-*), and some properties have no attribute.

This matters because Angular's square brackets set properties by default. That is what you want almost all the time, since properties are the live, typed values. But some things only exist as attributes, and for those Angular gives you attr.:

HTML
<td [attr.colspan]="columns().length">Total</td>
<button [attr.aria-expanded]="isOpen()" [attr.aria-controls]="panelId">Menu</button>
<li [attr.data-id]="item.id">{{ item.name }}</li>

Angular converts the value to a string and calls setAttribute. If the value is null or undefined, it calls removeAttribute instead, which is a neat way to add an attribute conditionally. (Boolean false is not the same as null: [attr.aria-expanded]="false" writes the text false, which is exactly what ARIA wants.) Without the attr. prefix, [aria-expanded] would fail, because there is no DOM property with that name; Angular reports unknown properties at compile time.

Here is the idea as a runnable stand-in. It models an element as an object with a table of attributes, a property bag, a set of classes and a style record, and applies each kind of binding to it. This is not how Angular is implemented; it just makes the four targets concrete.

TypeScript Four binding targets on a fake element

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that null removes an attribute but a property just receives the value. That asymmetry is real: for attributes, "no value" means "attribute absent."

Class bindings

There are three ways to add CSS classes, from simplest to most flexible:

HTML
<!-- 1. One class, on or off -->
<li [class.done]="task.done">{{ task.title }}</li>

<!-- 2. A string, an array or an object: replaces dynamic classes as one binding -->
<li [class]="rowClasses()">{{ task.title }}</li>

<!-- 3. The ngClass directive: the older, still-supported way -->
<li [ngClass]="{ done: task.done, urgent: task.urgent }">{{ task.title }}</li>

[class.done] toggles one class and leaves every other class alone, including the static ones you wrote with class="task". The [class] form accepts a string ('a b'), an array, or an object whose keys are class names and whose values decide on or off, so rowClasses() can be a computed signal returning { done: true, urgent: false }. Both forms are built in and need no import. ngClass (from NgClass) predates them and still works, but for new code the [class] binding is simpler.

Use class names for what the element is (done, selected, error), and put the colors in your stylesheet. That keeps styling out of your TypeScript.

Style bindings

Inline styles use the same shape:

HTML
<div class="bar" [style.width.%]="progress()"></div>
<p [style.color]="isError() ? 'crimson' : null">Status</p>
<p [style.font-size.px]="size()">Resizable</p>
<div [style]="{ backgroundColor: color(), opacity: 0.8 }"></div>

The part after the property name is an optional unit: [style.width.px]="120" writes 120px, and [style.width.%]="50" writes 50%. Both dashed (font-size) and camelCase (fontSize) names are accepted. Binding null removes the style, so the stylesheet value comes back. The object form [style]="{...}" is handy for a group of related values.

Prefer classes for anything that is a theme or state, and use [style.x] for values that really are data, such as a progress bar's width, a chart bar's height or a user-chosen color.

The ngStyle directive

Before [style] accepted objects, Angular had a directive for the same job: NgStyle. You will still meet it in older code and in the API docs, so it helps to know how it works.

TypeScript
import { Component, signal } from '@angular/core';
import { NgStyle } from '@angular/common';

@Component({
  selector: 'app-badge',
  imports: [NgStyle],
  template: `
    <span [ngStyle]="{ 'background-color': color(), 'font-size.px': size(), padding: null }">
      Hello
    </span>
  `,
})
export class BadgeComponent {
  color = signal('gold');
  size = signal(18);
}

The object maps style names to values. A key can carry a unit ('font-size.px'), and a null or undefined value removes that style. When the object changes, NgStyle compares it with the previous one and updates only the entries that differ, which is exactly what [style]="{...}" does today. For new code, prefer [style.x] or [style]: they need no import and keep the template shorter. Use NgStyle when you are maintaining code that already has it. Never use either one for static styling; put those rules in the component's stylesheet.

This stand-in re-creates the comparison so you can see which styles are written, kept and removed:

TypeScript Stand-in: what ngStyle changes on each update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

HTML in bindings and sanitization

What if the value is HTML? You can bind it to innerHTML:

HTML
<div [innerHTML]="article().bodyHtml"></div>

Putting untrusted HTML into a page is the classic route to cross-site scripting (XSS), so Angular sanitizes values bound to innerHTML (and to URL-like properties such as href and src, and to some style values). It removes things that can run code: <script> elements, on* event attributes and javascript: URLs. Harmless markup such as <b>, <em> and <a href="https://..."> survives. Interpolation never needs this, because {{ }} writes text, not HTML, and the browser cannot run text as code.

TypeScript
import { Component, inject } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-note',
  template: `<div [innerHTML]="trusted"></div>`,
})
export class NoteComponent {
  private sanitizer = inject(DomSanitizer);
  // Only do this for HTML you wrote or have already cleaned yourself.
  trusted: SafeHtml = this.sanitizer.bypassSecurityTrustHtml('<b>Hello</b>');
}

DomSanitizer.bypassSecurityTrustHtml (and the sibling bypassSecurityTrustUrl and others) turns the sanitizer off for that value. The name is a warning: never pass user input through it, because you take over the responsibility Angular was carrying. The security lesson (Security and Accessibility) comes back to this.

The next stand-in is an HTML page. It uses ordinary DOM code to mirror [prop], [class.x] and [style.x] from one piece of state, and it shows the difference between writing text and writing HTML. The "sanitizer" here is a deliberately tiny one that only strips script tags and on...= attributes; it is a teaching toy, not a security tool, and real sanitizers are far more thorough.

Binding state to properties, classes and styles

Type in the name box, tick the checkbox and drag the slider: each event updates the state object and one render() call re-applies every binding. In real Angular you never write that function. The compiler generates the equivalent update code and, with signals, runs only the parts whose inputs changed.

Which binding should I use?

flowchart TD
  A["What do you want to change?"] --> B{"Text inside an element?"}
  B -- yes --> C["Interpolation {{ value }}"]
  B -- no --> D{"A live DOM property or component input?"}
  D -- yes --> E["[property]=value"]
  D -- no --> F{"Something only in markup, like aria-* or colspan?"}
  F -- yes --> G["[attr.name]=value"]
  F -- no --> H{"CSS?"}
  H -- yes --> I["[class.x] for state, [style.x] for data"]

A quick decision guide for picking a binding.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does Angular bind to DOM properties by default instead of HTML attributes?

    Attributes are read when the HTML is parsed to set initial values. Properties are the live state, such as an input's current value, so binding to them is what you normally want.
  2. 2. Which binding is correct for setting aria-expanded, which has no DOM property of that name?

    The attr. prefix writes an attribute with setAttribute. Binding null or undefined removes the attribute again.
  3. 3. What does <div [style.width.px]="120"> produce?

    The optional unit after the style name is appended to the number, so you get 120px.
  4. 4. What does Angular do with a value bound to [innerHTML]?

    Angular's built-in sanitizer keeps harmless markup and strips content that can run code. Only bypassSecurityTrustHtml turns this off, and it should never be used with user input.

Summary

  • [prop]="expr" sets a DOM property or a component input whenever the expression's value changes.
  • Properties are live state; attributes are markup and initial values. Use [attr.name] for attributes without a property, and null removes them.
  • [class.name] toggles one class, [class] takes a string, array or object, and [style.prop.unit] sets one inline style (use it for real data such as widths).
  • Interpolation writes text; [innerHTML] writes HTML and is sanitized by Angular.
  • bypassSecurityTrust* disables sanitizing: never use it with data you do not control.
  • The runnable examples here are stand-ins that model the idea; the Angular snippets are read-only.

Next: Event Binding and $event