How to use <ion-segment> with dynamic values

I have values fetched from my REST APIs which need to be shown as multiple categories inside the view. So I am trying to use ion-segment, I managed to fetch the values as segments but I am not able to make them show and hide when I click them. With my code, both of them are not shown when I click any of them.

<ion-segment [(ngModel)]="selectedIdx" color="primary">
        <ion-segment-button (click)="changeMenus(i)" [value]="i" *ngFor="let team of teams; let i = index">
          {{team.teamname}}
        </ion-segment-button>
      </ion-segment>

      <div [ngSwitch]="selectedIdx" *ngFor="let team of teams">
          <ion-list *ngSwitchCase="team[i]">
            <ion-item>
              <h2>{{team.teamname}}</h2>
            </ion-item>
          </ion-list>
        </div>
  changeMenus(index:number)
  {
      this.selectedIdx=index;
  }

I did it like this…

I took two separate variables category for selected category to check for ngSwitch and categories which is my array that holds my dynamic values.

html:

<ion-content padding>
    <div padding>
        <ion-segment [(ngModel)]="category">
          <ion-segment-button *ngFor="let category of categories" value={{category}} (click)="Check()">
              {{category}}
          </ion-segment-button>
        </ion-segment>
      </div>
      <div [ngSwitch]="category">
      <div *ngFor="let category of categories">
        <ion-list *ngSwitchCase=category>
          <ion-item>
            <h2>{{category}}</h2>
          </ion-item>
        </ion-list>
      </div>
    </div>
</ion-content>

ts:

categories: any;
category: string;

in the constructor:
this.categories= [“ABC”,“DEF”,“GHI”];
this.category = “”;

the check function just prints the value of the category ngModel

It is working for me I hope it helps!

1 Like

Hi, this indeed works. But the problem is, the selected active segment is not highlighted. How to make the selected active segment becomes highlighted?

NotOk1

I noticed that if I remove the <div [ngSwitch]="category"> and all under it, it does highlight the active segment.
Ok

How to fix this? Any workaround?

Assuming you’re using the exact code posted previously, it has bound the segment to the category controller property. Assign a value to that property, and the corresponding segment will become selected.

I have figured out what happened: https://stackoverflow.com/questions/53386226/ionic-active-segment-not-highlighted-when-multiple-ngfor/53386820#53386820

In short, when we have another item under a segment, its container overlaps the bottom part of segment, thus the bottom border (which shows active segment) is hidden.