liveBook · Manning

Square bracket binding syntax

As explained in Pro Angular 16

Square bracket binding syntax is Angular template notation that marks a binding as one-way and supplies an evaluated expression to its target.

Square brackets mark an Angular template binding as one-way. Angular evaluates the expression between the quotes in the component’s context, then passes its result to a directive or property binding target. section 11.2 section 11.2.3

Read a square-bracket binding through its four parts:

  • Host element: the element whose appearance, content, or behavior changes. section 11.2
  • Target: a directive or property binding that receives the evaluated result. section 11.2
  • Expression: a JavaScript fragment that can use component properties and methods, including signal values. section 11.2
  • Direction: data flows from the expression to the target, unlike event or two-way bindings. section 11.2.3

Selecting a Bootstrap class

Use <div [ngClass]="classes()">Hello, World.</div> when the component’s classes method should determine the element’s class. A computed value can return "bg-success" when the model contains five objects and "bg-warning" otherwise. section 11.2

Passing expressions to a custom directive

Use [pa-attr]="products().length < 6 ? 'table-success' : 'table-warning'" or [pa-attr]="item.category == 'Soccer' ? 'table-info' : null". Angular evaluates each expression and supplies its result to the directive’s input property. section 14.3.2

Omitting the brackets changes the meaning: Angular passes the quoted content as literal text to a directive instead of evaluating it. Inspect the rendered DOM when a binding has no expected effect; literal class text commonly reveals the mistake. section 11.2.3 section 14.3.2

Listing 11.3. Appling a data binding in the template.html file in the src/app folder
<div [ngClass]="classes()" >
    Hello, World.
</div>

View the minimal ngClass binding that connects a host element with an evaluated component expression. section 11.2

How Pro Angular 16 covers it

How deep it goes
Explains host, target, expression, direction, custom inputs, and literal-value failures without descending into Angular binding internals.
Examples
Uses ngClass with a computed Bootstrap class and pa-attr with conditional, null, and fixed-string directive inputs.
What it assumes
Assumes component templates and JavaScript expressions while teaching bracket meaning, component context, and binding direction.
What you can do after
Apply it via Angular to evaluate component expressions for built-in or custom directive and property bindings.
How it connects
Connects one-way data binding with directives, property binding, string interpolation, event binding, and two-way binding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.