属性值绑定:方括号与花括号 [英] Attribute value binding: square brackets vs curly brackets
问题描述
我已经下载了适用于Node的Angular CLI 6.0.7,并且正在使用它,并按照教程等进行操作,以尽可能地学习。
I've downloaded Angular CLI 6.0.7 for Node and am playing around with it, following tutorials, etc. to learn as much as possible.
一件事我有一个关于数据绑定的问题。好像我想将组件成员变量的值(例如 title
)绑定到输入的值,我有两个选择:双花括号或方括号。这两种形式:
One thing I have a question about is data binding. It seems like if I wanted to bind the value of a component member variable, say title
, to an input's value, I have two options: double curly braces or square brackets. These two forms:
<输入[value] = title type = text />
<输入值= {{title}} type = text />
这两种方法之间是否有区别,还是仅仅是风格上的偏爱?如果存在功能上的差异,则在哪种情况下最好选择哪一个?
Is there any difference between those two approaches, or is it all just stylistic preference? If there's a functional difference, which one is preferred in which situations?
在此先感谢!
> EDIT 我知道大括号表示字符串插值,生成字符串,而方括号表示属性绑定,可以使用任何数据类型。但是我不明白的是,这两件事在功能上何时有所不同?
EDIT I understand that curly brackets denote string interpolation, resulting in a string, while square brackets denote property binding, which can use any data type. But what I don't understand is when are those two things functionally different? When would you ever have a DOM element's attribute contain a value that is not equivalent to its stringified version, and how would you even access such an attribute's value properly?
推荐答案
它们似乎相同,但是 {{}}
会将输入转换为字符串。但是,如果要输入数字或对象,则必须使用 []
。
They may seem to be the same but, {{ }}
will convert the input to a string. However if you want to input a number or an object, you must use [ ]
.
我包括了stackblitz 此处
I included a stackblitz representation for the same here
这篇关于属性值绑定:方括号与花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!