Search code examples
ionic-frameworkionic4

Programmatically scroll ion-segment


Is there any way to control scrolling on segments? In my case the slider and segments depends on each other and when you swipe slides, overflowwing segments does not slide, but active segment will be correctly choosed

My view and controller code:

<ion-segment scrollable mode="md" (ionChange)="segmentChanged()" [(ngModel)]="segment" color="warning">
  <ion-segment-button mode="md" value="0">
    <p>Description</p>
  </ion-segment-button>
  <ion-segment-button mode="md" value="1">
    <p>Interconnections</p>
  </ion-segment-button>
  <ion-segment-button mode="md" value="2">
    <p>Declensions</p>
  </ion-segment-button>
</ion-segment>

<ion-slides (ionSlideDidChange)="slideChanged()" pager="true">
  <ion-slide>
    First
  </ion-slide>
  <ion-slide>
    second
  </ion-slide>
  <ion-slide>
    third
  </ion-slide>
</ion-slides>

segmentChanged() {
    this.slider.slideTo(this.segment);
}

async slideChanged() {
    this.segment = await this.slider.getActiveIndex();
}

The segment itself works fine, but when swiping the active segment goes behind the screen.

enter image description here


Solution

  • I am also facing the same issue and finally solved the issue with below code.

    you must define the unique "id" for each "ion-segment-button"

    <ion-segment-button SwipedTabs *ngFor="let category of tabs ; let i = index"
            value={{category}} (click)="selectTab(i)" **id="segment-{{i}}**">
            <ion-label>{{category}}</ion-label>
          </ion-segment-button>
    
    .ts code 
    async slideChanged() {
        this.activeIndex= await this.slider.getActiveIndex();
          document.getElementById("segment-" + activeIndex).scrollIntoView({
          behavior: 'smooth',
          block: 'center',
          inline: 'center'
        });
    }
    

    hope it helps.