angular2内置指令

摘自ng2-book

1.NgIf

<div *ngIf="false"></div> <!-- never displayed -->
<div *ngIf="a > b"></div> <!-- displayed if a is more than b -->
<div *ngIf="str === 'yes'"></div> <!-- displayed if str holds the string "yes" -->
<div *ngIf="myFunc()"></div> <!-- displayed if myFunc returns a true value -->

2.NgSwitch

当ngIf判断条件过于复杂时用它!
ngSwitchDefault,可选。
ngSwitchWhen可重复匹配

<div class="container" [ng-switch]="myVar">
    <div *ngSwitchWhen="A">Var is A</div>
    <div *ngSwitchWhen="B">Var is B</div>
    <div *ngSwitchWhen="C">Var is C</div>
    <div *ngSwitchWhen="C">Var is C, too</div>
    <div *ngSwitchDefault>Var is something else</div>
</div>

3.NgStyle

为DOM设置css属性

//方法一
<div [style.background-color]="'yellow'">
    Uses fixed yellow background
</div>
//方法二
<div [ngStyle]="{color: 'white', 'background-color': 'blue'}"> 
    Uses fixed white text on blue background
</div>
//方法三:可动态赋值
<input type="text" name="color" value="{{color}}" #colorinput>
<input type="text" name="fontSize" value="{{fontSize}}" #fontinput>
<span [ngStyle]="{color: colorinput.value}">{{ colorinput.value }} text </span>
<div [style.background-color]="colorinput.value" style="color: white;">
    {{ colorinput.value }} background 
</div>

4.NgClass

//方法一:{key:value},key为类名,value为布尔值,表示该类是否启用
.bordered{
     border: 1px dashed black;
}
<div [ngClass]="{bordered: false}">This is never bordered</div> 
//方法二:动态赋值
<div [ngClass]="{bordered: isBordered}">
     This is a div with object literal. Border is {{ isBordered ? "ON" : "OFF"}}
</div>
还有一些方法用时再看

5.NgFor

<div class="ui list" *ngFor="#c of cities;#num = index""> 
  <div class="item">{{num+3}}{{ c }}</div>
</div>
//cities:数组。c:变量.index:索引

6.NgNonBindable

不编译,渲染纯字符串

<span class="pre" ngNonBindable>
    <- This is what {{ content }} rendered </span>
</div>
    原文作者:十七1991
    原文地址: https://segmentfault.com/a/1190000005030594
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞