I have recently started learning Angular2.
I want to know if there is a possibility to use ngSwitch or ngIf angular2
directives for a specific numeric range?
Say I want to update the color of some text based on a range.
<25 = Mark the text in red
>25 && <75 = Mark the text in orange
>75 = Mark the text in green
How do I achieve the same using Angular2 ngIf/ngSwitch directives.
Is there a way something to write like this ?
<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>
Or anything that would have to do with using ngSwitch, ngSwitchWhen statements.
With *ngIf
you would do it like this:
<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>
With [ngSwitch]
the syntax is like this:
<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>
Quick notes
*ngSwitchWhen
now works as *ngSwitchCase
item.status > 75
and above are automatically handled by *ngSwitchDefault
This might work, but I haven't tried it myself:
<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>
The idea is that when the expression is true, then return value
for *ngSwitchWhen
to match the [ngSwitch]
value.
I suggest you move the logic to the component, you'll have less boilerplate, and it's easier to work with:
<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";
}
Although you can write:
<div *ngIf="(item.status > 25) && (item.status < 75)">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With