jonnyhitek jonnyhitek - 1 month ago 39
TypeScript Question

Trying to access ionic 2 slides instance - returns undefined

however I am trying to use the slides. Then gain access to the instance so I can use the slideto functionality programmatically.

I have followed the documentation however I keep getting back undefined.

Below is page ts:

import { Component, ViewChild } from '@angular/core';

import { NavController, NavParams, Slides} from 'ionic-angular';

@Component({
selector: 'holiday',
templateUrl: 'holiday.html'
})
export class Holiday {


selectedItem: any;

@ViewChild('ghbslides') slider: Slides;
constructor(public navCtrl: NavController, public navParams: NavParams) {

console.log(this.slider); // returns undefined
this.selectedItem = navParams.get('holiday');

}

onSlideChanged(slide) {
console.log("slid");
}



}


And below is a snippet from my template where i define the slides:

<ion-slides #ghbslides (ionDidChange)="onSlideChanged(index)">

<ion-slide>
<h2>Slide 1</h2>
</ion-slide>

<ion-slide>
<h2>Slide 2</h2>
</ion-slide>

<ion-slide>
<h2>Slide 3</h2>
</ion-slide>

</ion-slides>


I have tried a few different things but each time this.slider is undefined.

Any help would be greatly appreciated hopefully I am missing something very obvious.

Answer

This is happening because the page is not loaded when the constructor is run. The slide will be defined after the view is loaded so you can override ionviewdidload to properly handle this.

ionViewDidLoad() {
        console.log(this.slider);
  }