[英]Why the ngStyle directive is declared into the []?
我是Angular 2的绝对初学者,并且我有以下与ngStyle指令的正确语法有关的问题 。
我有这个例子(工作正常):
<p [ngStyle]="{backgroundColor: getColor()}">Server with ID {{ serverID }} is {{ getServerStatus() }}</p>
我知道,在这种情况下, ngStyle指令将添加以下内容:
style="background-color: green;"
在我的HTML段落中。
我的疑问与该语法的正确含义有关。 为什么:
[ngStyle]="{backgroundColor: getColor()}"
并不是
ngStyle="{backgroundColor: getColor()}"
为什么要放入[...] ? 到底是什么意思?
这称为属性绑定 。 使用方括号,编译器将尝试对表达式求值。 没有它,您只是传递一个字符串。
因此,使用方括号,您正在传递一个javascript对象:
{
backgroundColor: getColor()
}
因此,编译器将从组件中调用getColor()
方法以获取正确的颜色。
另一方面,这里不讨论主题,但是如果您想在使用方括号时传递字符串,则应将其用单引号引起来:
<div [property]="'hiii'"></div>
Angular 2具有3种类型的指令:
ngStyle
是属性指令。 我们需要向其传递/分配值的所有属性指令都写在方括号内。 例如,“模板语法”指南中的内置NgStyle指令可以同时更改几种元素样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.