3

Why do we need to use square brackets for built-in Angular directives, like ngClass, ngStyle?

Example:

<some-element [ngClass]="'first second'">...</some-element>

Why not using like code below?

<some-element ngClass="'first second'">...</some-element>
Andrei Rosu
  • 1,169
  • 2
  • 10
  • 26

2 Answers2

3

All built-in directives, regardless of attribute or structural are denoted by enclosing square brackets. *ngFor and *ngIf are syntactical sugar (or shorthand syntax) for [ngForOf] and [ngIf]. See here.

Why the square braces? Because the in-built directives have the data bound to them using @Input decorator (examples: ngIf and ngClass). And as known before data are bound to @Input property using square brackets.

ruth
  • 29,535
  • 4
  • 30
  • 57
1

Check this good answer on template syntax. Also you will retrieve more details in Angular official docs

With your example, you could simply do :

<some-element class="first second">...</some-element>

Because in this example, you don't use the features of ngClass directive. Just set regular class via html attribute in this case.

But to invoke an Angular directive you should use square braces. Then in this case :

<some-element [ngClass]="{'first': isFirst, 'second': isSecond}"></someElement>

NgClass directive will add first class name to some-element if local property isFirst is true, and same thing for second.

Each directive has a selector to be invoked by Angular template compiler. In the case of NgClass, the selector is [ngClass].

Excerpt of source code :

@Directive({selector: '[ngClass]'})
export class NgClass implements DoCheck  {
...

Check for more details these resources : - Angular directives - Angular code for NgClass

Thierry Falvo
  • 5,892
  • 2
  • 21
  • 39