How to set the selected Segment

I am using ion-segment in my page, and I want to set one of the segment is selected segment whenever the page show, but it is not working if I use ngSelected=“selected”.

Anybody can advise how to set the selected segment as default segment whenever the page display?

Code:

<div>
  <ion-segment [(ngModel)]="testing">
    <ion-segment-button value="book">book</ion-segment-button>
    <ion-segment-button value="table">table</ion-segment-button>
  </ion-segment>
</div>
  <div [ngSwitch]="testing" >
    <ion-list *ngSwitchWhen="'book'" ngSelected="selected">
      <a ion-item>
        <ion-label>book list</ion-label>
      </a>
   </ion-list>
<ion-list *ngSwitchWhen="'table'">
      <a ion-item>
        <ion-label>table list</ion-label>
      </a>
   </ion-list>
</div>
4 Likes

in the js file for you component, in the constructor add:

this.testing = “table”;

This sets an initial value for “testing” to “table” making it the default segment on first entry to the page.

21 Likes

Thanks!, it worked for me

3 Likes

Thank you so much :relieved:

How do you set it on Ionic 3 ???

Still the same as before

hmm why I’m receiving ‘table’ is undefined ? :confused:

1 Like

Table , or whatever value you want to set, has to be a string inside quote marks.

You would only get that error if you were using it without the quotes, in which case javascript would look for a matching variable and fail to find it as none exists.

1 Like

ToDo:

testing:string

ionViewWillEnter(){
this.testing = “table”

}

3 Likes

This worked for me!!!

1 Like

Is there a way to set it without ngModel?

1 Like

If this.testing is type string work
If this.testing is type number NOT work
Thanks you

1 Like

Do you know how to make it work for number?
or do i have to convert from string to number in my code?

Thank you very much.Have a nice day!

your commentary saved me. I was using number… Thanks!! :grinning:

You need to initialize it in constructor like that
Code Behine

export class Segment{
   constructor() {      
     this.Select= "book";
 }
}

And Set in Html

<div>
  <ion-segment [(ngModel)]="Select">
    <ion-segment-button value="book">book</ion-segment-button>
    <ion-segment-button value="table">table</ion-segment-button>
  </ion-segment>
</div>
2 Likes

just write Selected in segment button

<ion-segment-button value="book" selected>book</ion-segment-button>

Thank you brother, works here!