angular6 中的 property-binding 和 attribute-binding

1.前言


前幾天,angular 項目裏實現屬性綁定的時候發現了個小問題,這是個人代碼:javascript

<input type="checkbox" [attr.checked]="item.data.isEnabled">html

但代碼並無生效。而後查了 angular 文檔裏的屬性綁定,文檔是這樣說的:java

HTML attribute vs. DOM property The distinction between an HTML attribute and a DOM property is crucial to understanding how Angular binding works.- Attributes are defined by HTML.數組

  • Properties are defined by the DOM (Document Object Model).
  • A few HTML attributes have 1:1 mapping to properties. id is one example.
  • Some HTML attributes don't have corresponding properties. colspan is one example.
  • Some DOM properties don't have corresponding attributes. textContent is one example.

Many HTML attributes appear to map to properties ... but not in the way you might think!That last category is confusing until you grasp this general rule: Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.The HTML attribute and the DOM property are not the same thing, even when they have the same name.app

上面那段話翻譯過來以下:ide

  1. Attributes 是由 html 定義的,而 Properties 是由文檔對象模型(DOM)定義的。
  2. 少許 html attributes 在 properties 裏造成 1:1 的映射關係,好比id;
  3. 一些 properties 沒有相應的 attributes,好比 td 中的 colspan, properties裏面就沒有 colspan;
  4. 一些 attributes 沒有相應的 properties,好比 textContent,attribute 就沒有textContent;

property 的值是能夠改變的,attribute 是不能夠改變的,HTML attribute 和 DOM property 雖然名字類似,可是不同的東西。如今,我以項目中的那句代碼爲例進行簡單分析。this

2.代碼示例

index.html:spa

<body>
 <div class="switch">
        <input type="checkbox" id="switchButton" name="switchButton" value="11" sth="whatevert">
        <label class="slider round" for="switchButton"></label>
 </div>
</body>
<script>
var attr = document.getElementById('switchButton');
    console.log(attr);
    console.log(attr.attributes)
</script>

其中執行 console.log(attr);打印出來的就是 property的內容:翻譯

從圖中能夠看到 DOM propertites 是對象數組,其中 checked:false 屬於 DOM properties 中的其中一項,而 attributes 是 properties 的一個名爲 NamedNodeMap 的子集,它的內容爲:code

能夠看到這個子集不是一個嚴格意義上的子集,由於 attributes 中的 sth="whatevert" 屬性,在 properties 上並無。執行下面代碼:

console.log(attr.sth);//underfined
console.log(attr.attributes.sth);//sth="whatevert"

3.總結

  1. 要實現 input 元素中 checked 屬性的綁定,應該是 [checked]="item.data.isEnabled"。當要實現某些 property 裏沒有,在attribute 裏的屬性時,應該用 [attr. ]="" 的綁定語法。
  2. 在 angular 裏一般是用 properties-binding 就能夠實現屬性綁定,某些特殊狀況下才須要 attribute-binding。
  3. HTML attibute 明確了屬性的初始值,而 DOM property 的屬性的值是當前的值。
  4. 最重要的一點:angular 裏說的模板綁定是指 property-dinding 和事件綁定,不包括 attribute-binding。
相關文章
相關標籤/搜索