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>
會導緻文法錯誤:
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')
The HTML attribute value specifies the initial value; the DOM value property is the current value.