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
