2

I want to display data dynamically as I retrieve it from the server ... so I need to bind to *ngSwitchCase

My code

<div class="main-content">
    <div class="segments-container" padding>
      <ion-segment [(ngModel)]="thisYearString" class="segments">
        <ion-segment-button value="{{thisYearNumber}}">
          {{thisYearNumber}}
        </ion-segment-button>
        <ion-segment-button value="{{lastYearNumber}}">
          {{lastYearNumber}}
        </ion-segment-button>
      </ion-segment>
    </div>
    <div [ngSwitch]="thisYearString">
      <ion-card *ngSwitchCase="'2017'" class="details-segment">
        <ion-card-header>2017</ion-card-header>
        <!--Some Other Code-->
      </ion-card>
      <ion-card *ngSwitchCase="'2016'" class="details-segment">
        <ion-card-header>2016</ion-card-header>
        <!--Some Other Code-->
      </ion-card>
    </div>
  </div>

What I want to to do is something like that:

*ngSwitchCase="{{thisYearString}}"

PS: I use String and Number since ngSwitchCase only accepts strings any ideas to overcome doing that too?

is it a good practice to add value dynamically like I did value="{{thisYearNumber}}"?

solimanware
  • 2,952
  • 4
  • 20
  • 40

1 Answers1

2

The structural directive already puts you in the right context to access your component variables.

If you do this:

*ngSwitchCase="thisYearString"

That will get the value from thisYearString defined in your component for the switch case. Also, I've been able to switch on non-strings (it is Javascript, after all) so I'm guessing it just coerces it before it does the check.

The reason you need quotes in your example here:

<ion-card *ngSwitchCase="'2017'" class="details-segment">

Around the 2017 is because otherwise it would try to treat that as a variable, and would fail.

Hardik Patel
  • 3,868
  • 1
  • 23
  • 37
chrispy
  • 3,552
  • 1
  • 11
  • 19