2

I am an absolute beginner with Angular 2 and I have the following dount related the correct syntax of the ngStyle directive.

I have this example (that works fine):

<p [ngStyle]="{backgroundColor: getColor()}">Server with ID {{ serverID }} is {{ getServerStatus() }}</p>

I know that, in this case, the ngStyle directive is adding something like to:

style="background-color: green;"

at my HTML paragraph.

My doubt is related the correct meaning of this syntax. Why is it:

[ngStyle]="{backgroundColor: getColor()}"

and not

ngStyle="{backgroundColor: getColor()}"

Why is it into the [...]? What it exactly means?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 2
    To make it simple : when you use `[directive]="..."`, it **sends data to the directive**. When you use `(directive)="..."`, the directive **sends data to you**. ngStyle is a built-in directive, if you look at the [documentation](https://angular.io/docs/ts/latest/api/common/index/NgStyle-directive.html), you can see what it does –  Jun 09 '17 at 10:45

2 Answers2

5

It's called property binding. With the brackets the compiler tries to evaluate the expression. Without it, you are just passing a string.

So with the brackets, you are passing a javascript object:

{
    backgroundColor: getColor()
}

Whereby the compiler will call the getColor() method from the component to get the right color.

On the other hand, and going off topic here, but if you want to pass a string while using brackets, you should wrap them in single quotes:

<div [property]="'hiii'"></div>
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • +1 for the last point. If you don't wrap the string like this "'hill'" and write it as "hill" then angular will try to find the variable hill instead of treating it as value. – Peter Jun 09 '17 at 10:21
3

Angular 2 has 3 types of directives:

  1. Attribute directives.
  2. Structural directives.
  3. Components.

ngStyle is an attribute directive. And all attribute directive to which we need to pass/assign values are written inside square brackets. The built-in NgStyle directive in the Template Syntax guide, for example, can change several element styles at the same time.

Peter
  • 10,492
  • 21
  • 82
  • 132