Why The Ngstyle Directive Is Declared Into The []?
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):
Solution 1:
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>
Solution 2:
Angular 2 has 3 types of directives:
- Attribute directives.
- Structural directives.
- 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.
Post a Comment for "Why The Ngstyle Directive Is Declared Into The []?"