Using branching logic
If a component's template needs to show different fragments based on the different values of an expression, you can use the Ngswitch series instructions to dynamically slice the template. For example, the ad component ezpromotion in the right-hand sample needs to push different ads depending on the gender of the Visitor:
Ngswitch contains a set of instructions for constructing a template that contains multiple branches :
Ngswitch
The ngswitch directive can be applied on any HTML element, it evaluates the value of the element's Ngswitch property, and, based on this value, determines which template 's content is applied (multiple branches can be displayed simultaneously):
1 [Ng-switch]= "expression" >...</any>
Ngswitchwhen
The ngswitchwhen directive must be applied on the child template element of the Ngswitch directive, which specifies an expression through the property ngswitchwhen, if the expression is consistent with the expression value specified by the ngswitch instruction of the parent node. Then display the contents of this template :
1 [Ng-switch]= "..." >2 <!--vs. variables-3 [ng-switch-when]= " Variable >...</template>4 <!--vs. Constants-5 ng-switch-when= "Constant" >...</template>6 </any>
Ngswitchdefault
The Ngswitchdefault directive must be applied on the child template element of the Ngswitch directive, and when there is no ngswitchwhen instruction match, Ngswitch will display the contents of the template:
1 [Ng-switch]= "..." >2 ng-switch-default= "" >...</template>3 </any>
It is important to note that the Ngswitch series directives are ANGUALR2 preset directives that need to be used prior to use in the template.
- Introduction of Ngswitch Series instructions from ANGULAR2 Library
- Declaration by Viewannotation's Directives property
For example:
1<!doctype html>234<meta charset= "Utf-8" >5<title>Interpolation</title>6<script type= "Text/javascript" src= "Lib/[email protected]" ></script>7<script type= "Text/javascript" src= "Lib/angular2.dev.js" ></script>8<script type= "Text/javascript" src= "Lib/system.config.js" ></script>9Ten<body> One<ez-app></ez-app> A<script type= "Module" > - //introducing the Ngswitch type -Import {component,view,bootstrap,Ngswitch,ngswitchwhen,ngswitchdefault} from "Angular2/angular2"; the -@Component ({selector: "Ez-app"}) - @View ({ - Directives:[ezpromotion], + Template: ' -<ez-promotiongender= "Female"></ez-promotion> + ` A }) at class ezapp{} - - @Component ({ -Selector: "Ez-promotion", -Properties["Gender"] - }) in @View ({ - Directives:[ngswitch,ngswitchwhen,ngswitchdefault], to Template: ' +<div[ng-switch]= "Gender"> -<templateng-switch-when= "Male"> the *</template> $<templateng-switch-when= "Female">Panax Notoginseng -</template> the<templateNg-switch-default> + A</template> the</div> + ` - }) $ class ezpromotion{} $ - Bootstrap (Ezapp); -</script> the</body> -ANGULAR2 Component Development-logical control of templates (ii)