[英]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. 我是Angular 2的绝对初学者,并且我有以下与ngStyle指令的正确语法有关的问题 。
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: 我知道,在这种情况下, ngStyle指令将添加以下内容:
style="background-color: green;"
at my HTML paragraph. 在我的HTML段落中。
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?
到底是什么意思?
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: 因此,使用方括号,您正在传递一个javascript对象:
{
backgroundColor: getColor()
}
Whereby the compiler will call the getColor()
method from the component to get the right color. 因此,编译器将从组件中调用
getColor()
方法以获取正确的颜色。
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>
Angular 2 has 3 types of directives: Angular 2具有3种类型的指令:
ngStyle
is an attribute directive. ngStyle
是属性指令。 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.
例如,“模板语法”指南中的内置NgStyle指令可以同时更改几种元素样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.