天天看點

angular6 中的 property-binding 和 attribute-binding

1.前言

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

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

但代碼并沒有生效。然後查了 angular 文檔裡的屬性綁定,文檔是這樣說的:

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.

上面那段話翻譯過來如下:

  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 雖然名字相似,但是不一樣的東西。現在,我以項目中的那句代碼為例進行簡單分析。

2.代碼示例

index.html:

<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的内容:

angular6 中的 property-binding 和 attribute-binding

從圖中可以看到 DOM propertites 是對象數組,其中 checked:false 屬于 DOM properties 中的其中一項,而 attributes 是 properties 的一個名為 NamedNodeMap 的子集,它的内容為:

angular6 中的 property-binding 和 attribute-binding

可以看到這個子集不是一個嚴格意義上的子集,因為 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。

版權聲明:本文為CSDN部落客「weixin_33975951」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_33975951/article/details/91795544

繼續閱讀