屬性聲明 - 暴露成員變量
屬性是組件暴露給外部世界的調用接口,調用者通過設置不同的屬性值來定制 組件的行為與外觀:
在Angular2中為組件增加屬性接口非常簡單,只需要在Component注解的properties屬性中聲明組件的成員變量就可以了:
1 //EzCard 2 @Component({ 3 properties:["name","country"] 4 })
上面的代碼將組件的成員變量name和country暴露為同名屬性,這意味着在EzApp的模板中,可以直接使用中括號語法來設置EzCard對象的屬性:
1 //EzApp 2 @View({ 3 directives : [EzCard], 4 template : "<ez-card [name]="'雷鋒'" [country]="'中國'"></ez-card>" 5 })
提醒:如果要在模板中使用自定義的指令(組件是一種指令),必須在View注解的directives 屬性中提前聲明!
例子如下:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>Property</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 {Component,View,bootstrap} from "angular2/angular2"; 15 16 //根組件 - EzApp 17 @Component({selector:"ez-app", 18 properties:["name","country"]}) 19 @View({ 20 directives:[EzCard], 21 template:` 22 <div class="ez-app"> 23 <h1>EzApp <b>{{name}}</b> <b>{{country}}</b> </h1> 24 <ez-card></ez-card> 25 </div>` 26 }) 27 class EzApp{ 28 constructor(){ 29 this.name = "Mike"; 30 this.country = "Sweden"; 31 } 32 } 33 34 //具有屬性接口的組件 - EzCard 35 @Component({ 36 selector:"ez-card", 37 properties:["name","country"] 38 }) 39 @View({ 40 template : `<div class='ez-card'> 41 My name is <b>{{name}}</b>, 42 I am from <b>{{country}}</b>.</div>` 43 }) 44 class EzCard{ 45 constructor(){ 46 this.name = "Mike"; 47 this.country = "Sweden"; 48 } 49 } 50 51 //渲染組件 52 bootstrap(EzApp); 53 </script> 54 </body> 55 </html>
結果如下: