[property] - 绑定属性
在模板中,也可以使用一对中括号将HTML元素或组件的属性绑定到组件模型的某个表达式, 当表达式的值变化时,对应的DOM对象将自动得到更新:
等价的,你也可以使用bind-前缀进行属性绑定:
1 @View({template:`<h1 bind-text-content="title"></h1>`})
很容易理解,通过属性,应用相关的数据流入组件,并影响组件的外观与行为。
需要注意的是,属性的值总是被当做调用者模型中的表达式进行绑定,当表达式变化时,被调用的组件自动得到更新。如果希望将属性绑定到一个常量字符串,别忘了给字符串加引号,或者, 去掉中括号:
1 //错误,Angular2将找不到表达式 Hello,Angular2 2 @View({template:`<h1 [text-content]="Hello,Angular2"></h1>`}) 3 //正确,Angular2识别出常量字符串表达式 'Hello,Angular2' 4 @View({template:`<h1 [text-content]="'Hello,Angular2'"></h1>`}) 5 //正确,Angular2识别出常量字符串作为属性textContent的值 6 @View({template:`<h1 text-content="Hello,Angular2"></h1>`})
例如:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>template - bind propery</title> 6 <script type="text/javascript" src="lib/system@0.16.11.js"></script> 7 <script type="text/javascript" src="lib/angular2.dev.js"></script> 8 <script type="text/javascript" src="lib/system.config.js"></script> 9 </head> 10 <body> 11 <ez-app></ez-app> 12 13 <script type="module"> 14 import {bind,Component,View,bootstrap} from "angular2/angular2"; 15 16 @Component({selector:"ez-app"}) 17 @View({ 18 template:`<h1 [style.color]="color">Hello,Angular2</h1>` 19 }) 20 class EzApp{ 21 constructor(){ 22 this.color = "red"; 23 } 24 } 25 26 bootstrap(EzApp); 27 28 </script> 29 </body> 30 </html>