I want the segments to scroll horizontally and, by default, scroll the selected segment button into view. I have the ion-segment object on a component that has vertical scrolling, which seems to work well for the scrolling part, but I haven’t been able to figure out how to scroll the selected segment into view. If anyone has done something like this, I’d love some help. How do I scroll into view a selected segment button? Do I have to use an ion-scroll object?
So I revisited this and came up with something that seems to be working in Chrome on the desktop that is emulating a mobile device. I haven’t checked it on a device yet.
// Scroll selected segment into view on mobile
if (this.platform.is('mobile')) {
var selectedValue = this.segment.value;
// I don't like working with underscore objects,
// but this seems *slightly* nicer than working with native elements at this point,
// and it seems to be the easiest way to find the selected index
var selectedIndex = this.segment._buttons.toArray().findIndex(function(button) {
return button.value === selectedValue;
});
// Of course, now I need to work with the native element...
var nativeSegment = <Element>this.segment.getNativeElement();
// I pass in false to keep my page from scrolling vertically. YMMV
nativeSegment.children[selectedIndex].scrollIntoView(false);
}
This is after setting up the CSS to do scrolling. In my case, the ion-segment object is wrapped in a custom component of mine, so I have the scrolling CSS on that element instead of directly on the ion-segment, but it’s basically the same as the CSS in https://github.com/driftyco/ionic/issues/7202.
First off, import needed objects from @angular/core and ionic-angular, of course. The segment object above comes from a @ViewChild(Segment) segment: Segment;
When should you do this? Well, since my segments are being used as navigation to pages that are then set as root on my current tab, and since I am using the workaround for the ion-segment-button *ngFor issue, I run this in my ViewController's didEnter. That may not be the right spot for anyone else, but it seems to be working for me.