Ionic Slider

In ionic have pre built slider component. The Slides component is a multi-section container. Each section can be swiped between each other. We can have any number of slider inside the slides.

In Slider, it is not necessary to add an event listener. If we need an additional feature like getting the index number of av slide. We can also add events to listen to on the element. Let’s add the ionSlideDidChange event and call a method when the slide changes:

Add the following code in HTML page template.

<ion-header> ...</ion-header>
 
<ion-content>
    <ion-slides #mySlider index=0 (ionSlideDidChange) = "onSlideChanged($event)">
        <ion-slide style="background-color: green">
            <h2>Slide 1</h2>
        </ion-slide>
        <ion-slide style="background-color: blue">
            <h2>Slide 2</h2>
        </ion-slide>
        <ion-slide style="background-color: red">
            <h2>Slide 3</h2>
        </ion-slide>
    </ion-slides>
</ion-content>

To get the event in the slider, we add ionSlideDidChange event binding of ionic on ion-slides directive, whenever slider event is detected by ionislide, it will call the onSlideChanged() method.

Add the following code in page.ts

import { Component, ViewChild } from '@angular/core';
import { Slides, NavController } from 'ionic-angular';
 
@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html'
})
 
export class ContactPage {
    @ViewChild('mySlider') slider: Slides;
     
    constructor(public navCtrl: NavController) {
    }
     
    ionViewWillEnter(){
        console.log('Enter Page 3');
    }
     
    onSlideChanged(e) {
        let currentIndex = this.slider.getActiveIndex();
        console.log("You are on Slide ", (currentIndex + 1));
    }
}

We need to import slides and viewChilde. In an angular, we have @ViewChild decorator which allow us to interact with parent and child component. ViewChild helps us to get access to a component and its methods of the parent component.
You can use ViewChild to get the first element or the directive matching the selector from the view DOM. If the view DOM changes and a new child matches the selector, the property will be updated.