To bind to an element’s property, enclose it in square brackets, [], which identifies the property as a target property. A target property is the DOM property to which you want to assign a value. For example, the target property in the following code is the image element’s src property.
<img [src]="itemImageUrl">
1
这个语法里,数据从Component的itemImageUrl流向img标签的src属性。中括号里的src属性是被赋值的target.
中括号告诉Angular,将中括号等号右边的值当成动态表达式处理。如果去掉中括号,等号右边的值被当成纯粹的静态字符串处理。
The brackets, [], cause Angular to evaluate the right-hand side of the assignment as a dynamic expression. Without the brackets, Angular treats the right-hand side as a string literal and sets the property to that static value.
Angular里容易混淆的property和attribute的区别
一个例子:
A common point of confusion is between the attribute, colspan, and the property, colSpan. Notice that these two names differ by only a single letter.
colspan是attribute,而colSpan是property.
下面的代码:
<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
1
会导致语法错误:
Template parse errors:
Can’t bind to ‘colspan’ since it isn’t a known native property
原因很简单,td的原生property为colSpan,而不是colspan.
Interpolation and property binding can set only properties, not attributes.
Interpolation和property binding都只对property生效,而非attribute.
Data binding works with properties of DOM elements, components, and directives, not HTML attributes.
Attributes initialize DOM properties and you can configure them to modify an element’s behavior. Properties are features of DOM nodes.
Properties是DOM节点的特性。
A few HTML attributes have 1:1 mapping to properties; for example, id.
有一些html属性有一一对应的property值,比如id
Some HTML attributes don’t have corresponding properties; for example, aria-*.
有些html属性缺乏一一对应的property,比如aria-*系列的属性,就没有对应的DOM property
Some DOM properties don’t have corresponding attributes; for example, textContent.
有些DOM property没有对应的attribute,比如textContent.
In Angular, the only role of HTML attributes is to initialize element and directive state.
在Angular应用里,html attribute的唯一作用,就是初始化element和Directive的状态。
看个例子:
When the browser renders , it creates a corresponding DOM node with a value property and initializes that value to “Sarah”.
当浏览器渲染input节点时,创建对应的DOM节点,value property赋值为Sarah.
然后用户在input里输入Jerry,DOM节点的value property值变为Jerry,然而用下列代码查看value attribute的值,仍然是Sarah:
input.getAttribute('value')
1
The HTML attribute value specifies the initial value; the DOM value property is the current value.