Angular2組件開發—模板的邏輯控制(二)

使用分支邏輯

若是組件的模板須要根據某個表達式的不一樣取值展現不一樣的片斷,能夠使用NgSwitch系列指令來動態切分模板。好比右邊示例中的廣告組件EzPromotion,須要根據來訪者性別的不一樣推送不一樣的廣告:javascript

NgSwitch包含一組指令,用來構造包含多分支的模板html

NgSwitchjava

NgSwitch指令能夠應用在任何HTML元素上,它評估元素的ngSwitch屬性值,並根據這個值 決定應用哪些template的內容(能夠同時顯示多個分支):express

1 <any [ng-switch]="expression">...</any>

NgSwitchWhenbootstrap

NgSwitchWhen指令必須應用在NgSwitch指令的子template元素上,它經過屬性ngSwitchWhen指定一個表達式, 若是該表達式與父節點的NgSwitch指令指定的表達式值一致,那麼顯示這個template的內容angular2

1 <any [ng-switch]="...">
2     <!--與變量比較-->
3     <template [ng-switch-when]="variable">...</template>
4     <!--與常量比較-->
5     <template ng-switch-when="constant">...</template>
6 </any>

NgSwitchDefaultapp

NgSwitchDefault指令必須應用在NgSwitch指令的子template元素上,當沒有NgSwitchWhen指令匹配 時,NgSwitch將顯示這個template的內容:spa

1 <any [ng-switch]="...">
2     <template ng-switch-default="">...</template>
3 </any>

須要注意的是,NgSwitch系列指令都是Angualr2的預置指令,在模板中使用以前,須要code

  1. 從Angular2庫中引入NgSwitch系列指令
  2. 經過ViewAnnotation的directives屬性進行聲明

例如:htm

 1 <!doctype html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>Interpolation</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     <script type="module">
13         //引入NgSwitch類型
14         import {Component,View,bootstrap,NgSwitch,NgSwitchWhen,NgSwitchDefault} from "angular2/angular2";
15         
16         @Component({selector:"ez-app"})
17         @View({
18             directives:[EzPromotion],
19             template:`
20                 <ez-promotion gender="Female"></ez-promotion>
21             `
22         })
23         class EzApp{}
24         
25         @Component({
26             selector : "ez-promotion",
27             properties:["gender"] 28         })
29         @View({
30  directives:[NgSwitch,NgSwitchWhen,NgSwitchDefault], 31             template : `
32                 <div [ng-switch]="gender">
33                     <template ng-switch-when="Male">
34                         <img src="img/male-ad.jpg">
35                     </template>
36                     <template ng-switch-when="Female">
37                         <img src="img/female-ad.jpg">
38                     </template>
39                     <template ng-switch-default>
40                         <h1>Learn Something, NOW!</h1>
41                     </template>                    
42                 </div>
43             `
44         })
45         class EzPromotion{}
46         
47         bootstrap(EzApp);
48     </script>
49 </body>
50 </html>
相關文章
相關標籤/搜索