2016-06-14 53 views
3

我最近開始學習Angular2。在Angular 2的數值範圍內使用ngSwitch

我想知道是否有使用ngSwitch或ngIf angular2

指令的特定數值範圍內的可能性?

說我想根據範圍更新一些文本的顏色。

<25 = Mark the text in red 
>25 && <75 = Mark the text in orange 
>75 = Mark the text in green 

如何使用Angular2 ngIf/ngSwitch指令實現相同。

有沒有辦法寫這樣的東西?

<div [ngIf]="item.status < 25"> 
<h2 class="text-red">{{item.status}}</h2> 
</div> 
<div [ngIf]="item.status > 25 && item.status < 75"> 
<h2 class="headline text-orange">{{item.status}}</h2> 
</div> 
<div [ngIf]="item.status > 75"> 
<h2 class="headline text-green">{{item.status}}</h2> 
</div> 

或者任何與使用ngSwitch,ngSwitchWhen語句有關的事情。

回答

2

隨着*ngIf你會做這樣的:

<div *ngIf="item.status < 25"> 
    <h2 class="headline text-red">{{item.status}}</h2> 
</div> 
<div *ngIf="item.status > 25 && item.status < 75"> 
    <h2 class="headline text-orange">{{item.status}}</h2> 
</div> 
<div *ngIf="item.status > 75"> 
    <h2 class="headline text-green">{{item.status}}</h2> 
</div> 

隨着[ngSwitch]語法是這樣的:

<div [ngSwitch]="true"> 
    <h2 *ngSwitchCase="item.status < 25" class="headline text-red">{{item.status}}</h2> 
    <h2 *ngSwitchCase="item.status > 25 && item.status < 75" class="headline text-orange">{{item.status}}</h2> 
    <h2 *ngSwitchDefault class="headline text-green">{{item.status}}</h2> 
</div> 

快速筆記

  • *ngSwitchWhen現在作爲*ngSwitchCase
  • 情況下,像item.status > 75以上是由*ngSwitchDefault
1

這可能會實現,但我還沒有嘗試過自己:

<div [ngSwitch]="value"> 
    <p *ngSwitchCase="'init'">increment to start</p> 
    <p *ngSwitchCase="item.status < 25 ? value">a</p> 
    <p *ngSwitchCase="item.status > 25 && item.status < 75 ? value ">c</p> 
    <p *ngSwitchCase="item.status > 75 ? value">d</p> 
    <p *ngSwitchDefault>else</p> 
</div> 

的想法是,當表達式爲真,則返回value*ngSwitchWhen匹配[ngSwitch]值。

1

自動處理,我建議你移動邏輯組件,你可以少樣板,而且它更容易使用:

<div> 
    <h2 [class]="switchClass(item.status)">{{item.status}}</h2> 
</div> 

switchClass(item.status) { 
    if (item.status < 25) return "text-red"; 
    else if (25 < items.status && item.status < 75) return "headline text-orange"; 
    else if (75 < items.status) return "headline text-green"; 
} 

雖然你可以這樣寫:

<div *ngIf="(item.status > 25) && (item.status < 75)"> 
0

在處理angular2有條件的造型,最好使用[class]當你添加一個類或[ngClass]當你正在返回一個像這樣的類的數組:headline text-green someOtherClass

// display div 
<div [ngClass]="getItemClass(item.status)">{{item.status}}</div> 

// logic 
getItemClass(status) { 
    let itemClass: string; 

    if (status < 25) { 
    itemClass = 'text-red'; 
    } else if (status > 25 && status < 75) { 
    itemClass = 'headline text-orange'; 
    } else { 
    itemClass = 'headline text-green'; 
    } 

    return itemClass; 
} 

類似的,而不是宣佈itemClass作爲一個字符串,我們可以宣佈它作爲一個數組,在這種情況下即let itemClass: Array<string>;我們重新分配它在我們如果塊作爲itemClass = ['headline', 'text-green']。這工作正常。