2
votes

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?

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, you can see what it doesuser4676340

2 Answers

4
votes

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>
2
votes

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.