Angular指令

Angular提供了若干內置指令,下面來看看它的神奇:

ngIf

如果要實現一個元素的顯示與隱藏,ngIf指令的表達式將會實現這個功能:

<div *ngIf="b">我是一個盒子</div>  //這裏的b最終的結果是一個boolean值,b可以是表達式、函數、判斷語句等等

ngSwitch

在需要根據不同的條件來渲染不同的元素時,此時用ngIf會感覺特別的繁瑣,ngSwitch解決了這一問題:

<div [ngSwitch]="myBook">    //myBook是一個字符串變量   J、Q、K是變量的隨機值,*ngSwitchDefault是默認值
  <div *ngSwitchCase="'J'">book is J</div>   
  <div *ngSwitchCase="'Q'">book is Q</div>
  <div *ngSwitchCase="'K'">book is K</div>
  <div *ngSwitchDefault>default</div>
</div>

ngStyle

使用ngstyle最大的特點就是給DOM元素動態的天劍CSS屬性,它有兩種寫法:

1.  [style.<cssproperty>]="value"的形式:

eg  :

<div [ngStyle.background-color]="'yellow'">yellow</div>

<div [ngStyle.color]="red">yellow</div>

注意:在上面的例子中我給background-color使用了單引號,而color並未使用,這是因爲ngStyle是一個JavaScript對象,color是一個合法的鍵,不需要引號,但是background-color是一個連字符,連字符是不允許出現在對象的鍵名當中的,除非是一個字符串,故而使用了單引號。

2.  使用鍵值對的形式:鍵值對裏面還可以使用條件語句

eg:  

 <div [ngStyle]="{color:'red',width:'10px'}"></div>

 <div [ngStyle]="{color:Codevalue?'red':'lightblue'}"></div>    亮色字體部分是一個三元表達式(常用)

ngClass

ngClass指令在HTML模板中用ngClass屬性表示,可以動態設置和改變DOM元素的CSS類:

eg: 

第一種情況:普通的添加CSS類

css

  .bordered{ border:1px dashed black;  background-color:#ccc;} 

html:

<div [ngClass]="{bordered:true}">這是帶邊框的box</div>

<div [ngClass]="{bordered:false}">這是沒有邊框的box</div>

第二種情況:設置變量動態的賦予不同的CSS類

eg:  

css: 

.bordered{ border:1px dashed #cecece }

.colored{ color:lightblue  }

html:  

<div [ngClass]="{isBordered?'bordered':'colored'}">是你有不一樣的邊框的呢還是我的顏色更亮麗一些的呢</div>

TS:  

export  class NgClassSampleApp {

isBordered:boolean;  //如果爲true渲染出來的爲有邊框的字,false的話渲染爲帶lightblue色的字

}

ngFor

重複一個給定的DOM元素(或一組DOM元素),渲染時,每次重複都會從數組中取一個新的值,它的語法結構是:

*ngFor="let item of items ;let i= index"

  • let item 語法是用來接收items數組中的每一個元素的變量。
  • items是來自控制器的一組項的集合。
  • let i= index是爲了獲取數組的索引,這個跟JavaScript一樣,從零開始,以此例推 。

eg:

TS: 

 this.people=[

{name:'關羽',argument:'五虎上將',country:'蜀國' },

{name:'曹操',argument:‘大帥’,country:'魏國' },

{name:'周瑜',argument:‘軍師’,country:'吳國' }

]

html:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Argument</th>
      <th>Country</th>
    </tr>
  </thead>
  <tr *ngFor="let item of people">
    <td>{{item.name}}</td>
    <td>{{item.argument}}</td>
    <td>{{item.country}}</td>
  </tr>
</table>

result:

NameArgumentCountry
關羽五虎上將蜀國
曹操大帥魏國
周瑜軍師吳國

ngNonBindable

這個指令一般情況下用的少,當我們在也界面中不想編譯某一部分的時候,這個見例子會更好明白:

eg:

html:

<div class="noned">
  <span class="bordered">{{content}}</span>
  <span class="pre" ngNonBindable>
  ←這是{{content}}
  </span>
</div>

TS:

content:string ='王者農藥';

result:

        『王者農藥』  這是content;



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章