Ionic3 sliding segments
Ionic has a very beautiful feature of ‘Segments’. The feature itself is pretty great and easy to implement, but it lacks ability to swipe between segments, especially in case of a mobile app.
So, let’s add a swipeable segment functionality for mobile applications built using Ionic 3. Let’s begin by creating a demo app.
Let’s create a demo app
ionic start myApp blank && cd myApp
Add a mobile platform to it(adding android)
ionic cordova platform add android
Create a directive named as ‘SwipeSegmentDirective’ which is going to handle the swipe among segments
Few responsibilities of this directive
- Maintain list of all the segments
- Add and listen for swipe event on the parent element
- Check and notify the parent component in case a swipe occurred and we are allowed to move forward/backward
Add the newly created directive in “app.module.ts” as dependency
Open ‘src/pages/home/home.ts’, replace the content with below code
Few things to notice
public category: string = 'movies';public categories: Array<string> = ['movies', 'tvshows', 'animated']
- ‘category’ a string responsible to hold current selected tab
- ‘categories’ an array containing list of all tabs. This array is passed to our directive in order to maintain the swiping order
Open ‘src/pages/home/home.html’, replace the content with below code
We are passing list of categories to directive with a callback function, which decides which tab is going to presented to user after swipping the screen.
<div [ngSwitch]="category" swipeSegment [tabsList]="categories" [(currentTab)]="category" (tabChanged)="onTabChanged($event)" class="swipe-area">
As, we want swipe to work across the whole content whole. Open ‘src/pages/home/home.scss’ and add the following class
Time to save our files and run the app to see the segment swiping live in action
ionic cordova run android -l -c
Swipe across the different segments and see the magic yourself.
To see it live in action, please checkout ‘Info’ & ‘Scorecard’ sections of ‘Crazy Tic Tac Toe’, available on Google play store.
I hope you’ve enjoyed reading, complete source code is available at ‘GitHub’. Happy coding!