Angular 4:Directive

這邊記錄幾個Angular 的directive使用方法:
分別為

1. ngIf
2. ngIf-else
3. ngStyle
4. ngClass
5. ngFor


1. ngIf

ngIf所接受的內容是回傳true與false的內容,可以是變數或是function
ngIf使用方法:


<HtmlElement *ngIf="變數/ function"></HtmlElement>
ngIf前面一定要加上星號。

<p *ngIf="expression"> NG-IF server created.</p>

在ngIf條件為false時,該Element不會出現在DOM中,直至ngIf的條件變成true時才會新增在DOM。


2. ngIf-else

到了Angular 4新增加了else的功能,需要搭配ng-template使用,直接看範本:
<p *ngIf="expression; else noServer"> NG-IF server created.</p>
<ng-template #noServer>
    <p>No server added.</p>
</ng-template>


從上面可以看到到,ngIf的用法與之前相同,但若要使用else功能,則是在ngIf的expression後加上分號,接著加上else mark,ng-template處加上 #mark,讓else條件可以參考到,表示if條件不成立時,要切換的畫面,如此在滿足ngIf條件時,ng-template的內容就不會顯示,若不滿足ngIf條件時,則改由ng-template的內容顯示。

3. ngStyle

可以透過ngStyle來改變一個HTMLElement的css屬性,透過attribute binding的方式使用ngStyle:

<p [ngStyle]="{backgroundColor: getColor()}"></p>

其中backgroundColor也可以寫成background-color,getColor是在Angular內自己定義的function,透過getColor來取得顏色,function內回傳像是'red'的內容即可,因此要顯示的顏色邏輯就可以在程式內控制,可以動態切換Element的style。

4. ngClass

ngStyle是可以動態改變HTMLElement的css style,則ngClass是可動態改變HTMLElement的class,方法同樣是以attribute binding的方式,

<p [ngClass]="{className: expression}"></p>
方法比較像是達到某條件時,則使用特定class,前面放的是要使用的class名稱,condition則是達到什麼條件要使用該class,例如
[ngClass]="{online: serverStatus==='online'}"

5. ngFor

透過ngFor可以產生多個同樣的HTMLElement,如果有一個有一個陣列:servers,如果希望servers內有多少值就重複產生多少個<div>,透過ngFor可以寫成

<div *ngFor="let server of servers"></div>

其中server是每一個在servers內的Element,servers是資料來源。

如果要知道現在的server是servers中的第幾個,ngFor有一個變數專門用來記錄當前是第幾個iteration,所以要知道目前是第幾個,只要將index指定到一個變數即可。
<div *ngFor="let server of servers; let i=index" ></div>

在ngFor內加入
let i = index
index表示現在的server是servers陣列中的第幾個,如果需要額外透過索引做判斷,則可以在function內傳入 i變數,像是
<div *ngFor="let server of servers; let i=index" [ngStyle]="{background: getBackgroundColor(i)}" >
在getBackgroundColor function內即可拿到當前的iteration是多少。
在let i = index前一定要記得加入分號


沒有留言:

張貼留言

Java Spring Framework 筆記 - Autowiring (2)

這篇記錄透過 Annotation來做到 Spring的 autowiring。