Ionic 3 swipeable tabs
Nearly 6 months ago, I’ve published an article about how to create ‘Ionic 3 swipeable segements’. Today, we are going to create similar effect for ‘Ionic tabs’.
There are several great approaches out there to create sliding effect for ionic tab, but how about a solution where we don’t need to make too many changes in new/existing applications and be able to achieve the swipe effect. So we are going to create a directive which will handle everything for us.
Let’s get started by creating a demo app with tabs
ionic start ionic3-swipeable-tabs tabs && cd ionic3-swipeable-tabs
Create a directive which should fulfill the following responsibilities:
- Directive should be able to work from root tab element ‘ion-tabs’
- As swipe gesture doesn’t work on ‘ion-content’, hence insert and wrap an element as child of ‘ion-content’
- Add swipe ‘Gesture’ on tab content depending whether we are on touch device or desktop. As we are adding our HTML content dynamically the swipe event wasn’t working with it, as a result I’ve added a pure solution to handle the swipe ‘Gesture’ for touch devices
- Depending on swipe direction and possibility to move, notify the root tab component to change the tab
- Remove all event listeners once tabs components are getting deleted from DOM
Lets look closely in directive
- tabCount — keeps the count of number of tabs we need to cater
- onTabInitialized — called once tab is active, checks whether we already have our html content injected to handle the swipe event
- createWrapperDiv — creates a wrapper div inside ion-content to wrap its child elements and add swipe event listener
- Rest, we have our functions to handle the swipe events
Time to utilize this directive in our application. Declare the directive in app.module.ts
Modify the tabs.html and add ‘swipeTab’ directive in it
Make following changes to tabs.ts to communicate with swipe directive
Add following css in variable.scss
.swipe-area {
height:100%;
width:100%;
}
Save all of your files and run the application to see the tabs swiping live in action
ionic serve
Let me know in the comments below, if I’ve left out anything or got any question.
I hope you’ve enjoyed reading, complete source code is available at ‘GitHub’. Happy coding!