当咱们查看Angular的代码,须要给属性绑定一个变量时,一会用[property]="variable"
,一会用property="{{variable}}"
,有时候还有[attr.property]
,究竟他们有什么区别?
先把结论搁在这
Angular 官方文档在绑定属性几乎都是使用[],而插值表达式{{}}更可能是用于显示,二者最大的区别就是后者会将{{}}语句里执行完的值再转换string 类型。html
实践是检验真理的惟一标准,先写一个简单的测试componenttypescript
@Component({ selector: 'my-here', template: `<br>2333333333333333{{here}}` }) export class HereComponent { @Input() here: any; @Input() whichone: string; ngOnChanges(change){ console.log(this.here) console.log(change) } }
使用它json
<my-here [herestr]="poo" [whichone]="'[]'"></my-here> --------------------------- <my-here herestr="{{poo}}" [whichone]="'{}'"></my-here>
poo是一个string,而且咱们经过input 或者button 改变poo 的值,二者在页面的显示和在控制台的打印都正常,看起来并无差别。
但是咱们发现,当poo 还没赋值的时候,前者打印是的undefined,后者是''空字符串,估计是后者把undefined 换成'',却又并非单纯的转换类型,由于undefined 转string 的话应该是字面量'undefined',可是能够肯定的是经过{{}}得到的必定是string 类型。浏览器
试试给poo 送一个object,{{}}获得的是"[object Object]",证明了咱们的猜测。ide
那Angular 里还有一种attribute 绑定,写法是[attr.Attribute]="variable"
,那这个[property]="variable"
又有什么区别呢?
首先咱们得搞清楚Dom的property(属性) 和 attribute(特性),简单来讲测试
<div id="test"></div>
例若有一个element var testElm = document.getElementById('test')
这个element 的id 特性是 testElm.getAttribute('id')
,而它的id 属性是testElm.id
DOM element 只有基本特性会有一一对应的属性,例如id、title等,若是咱们添加一个自定义特性diyui
<div id="test" diy="whatever"></div>
那么testElm.getAttribute('diy')
或者testElm.attributes[1]
就是它的diy 特性,可是它并无对应的diy 属性,一样状况的还有一些ARIA attribute 和table 中的colspan/rowspan。this
ARIA指可访问性,用于给残障人士访问互联网提供便利
对于自定义属性,H5有一个data-* 的特性,例如spa
div id="test" data-diy="whatever"></div>它的特性就是
testElm.getAttribute('diy')
,而对应的属性则是testElm.dataset.diy
翻译
ok,说回Angular,因为element没有这些属性,中括号[]的属性绑定语法天然不行,并且编译模板时会报错,因此对于非基本属性,Angular 提供了这种[attr.Attribute]="variable"
的特性绑定语法。
by the way,当property是基本属性时,使用[property]="variable"
绑定属性,而后改变variable 的值,对应的attribute也会跟着属性同步,Angular应该是作了属性和特性的数据双向绑定的工做
因此只有property是基本属性,二者同样,例如[id]
和[attr.id]
的做用并没有区别。
道理我都懂,但为何鸽子辣么大.....这有什么用呢,emmmmmm固然有,最多见的就是[property]="false"
和property="{{false}}"
的差别,后者其实绑定的是'false',一旦作if语句就有问题。
综上所诉,属性绑定最好仍是用中括号,双大括号用于展现,如<div>{{obj | json}}</div>
,实际上,在渲染视图以前,Angular 把这些插值表达式翻译成相应的属性绑定。
还有就是,它依然能够用于执行Angular的模板语法,例如property="{{fun()}}"
,property="{{a?b:c}}"
,只是它会作多一步:把return的值转换成string。
说到attribute 和 property,记录个坑,Input标签的maxlength 特性对应的是maxLength 属性,即便特性写成大写maxLength 以下,浏览器解析出来的依然是<input maxlength="10" />
<input maxLength="10" />
因此写成[attr.maxlength]、[attr.maxLength]、[maxLength]
都是能够,可是[maxlength]
就不行,minlength/minLength同样。
Angular模板语法
DOM 中 Property 和 Attribute 的区别