天天看点

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

继续阅读