Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ngSwitch on a numeric range in Angular 2

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.

like image 789
this-Me Avatar asked Jun 14 '16 08:06

this-Me


3 Answers

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

  • The old *ngSwitchWhen now works as *ngSwitchCase
  • Cases like item.status > 75 and above are automatically handled by *ngSwitchDefault
like image 129
rinukkusu Avatar answered Oct 21 '22 01:10

rinukkusu


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.

like image 2
Günter Zöchbauer Avatar answered Oct 21 '22 02:10

Günter Zöchbauer


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)">
like image 1
Sasxa Avatar answered Oct 21 '22 00:10

Sasxa