为什么将ngStyle指令声明为[]? [英] Why the ngStyle directive is declared into the []?

查看:74
本文介绍了为什么将ngStyle指令声明为[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用 Angular 2 的绝对初学者,并且我有以下与 ngStyle 指令的正确语法有关的内容.

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>

我知道,在这种情况下, ngStyle 指令将添加以下内容:

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

style="background-color: green;"

在我的HTML段落中.

at my HTML paragraph.

我的疑问与该语法的正确含义有关.为什么呢?

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

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

不是

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.

因此,使用方括号,您正在传递一个javascript对象:

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

{
    backgroundColor: getColor()
}

由此,编译器将从组件中调用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>

这篇关于为什么将ngStyle指令声明为[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆