Ionic 2 Slides Component - How to Access Swiper AP

2019-04-05 19:17发布

问题:

Using ion-slides component (4 slides) on app welcome page/slides. I need ability for user to skip to last slide. Docs say ion-slides implementation of Swiper API. I need to access methods like: mySwiper.slideTo(index, speed, runCallbacks);

Tips on how to implement?

回答1:

You can pass a function within the options property.

Original answer.

@Component({
  selector: 'my-component',
  template: '<ion-slides [options]="options">
               <ion-slide>Slide1</ion-slide>
               <ion-slide>Slide2</ion-slide>
             </ion-slides>',
  directive: [IONIC_DIRECTIVES]
})
export class MyComponent {
  public slider: any;

  constructor() {
    this.options = {
      onlyExternal: false,
      onInit: (slides: any) =>
        this.slider = slides
    }
  }

  click() {
    this.slider.sliderNext(true, 250);
  }
}

For further options have a look at the swiper api.



回答2:

If you are looking for a simple solution without custom directives, you can try this

  constructor(
    private _app: IonicApp
  ){}
  ngAfterViewInit() {
    this._slider = this._app.getComponent('my-slider');
  }
  goToSlide(slideIndex){
    this.slider.slider.slideTo(slideIndex);
  }


回答3:

You can make a service with your Swiper

@Injectable()
export class HomeSwiper {
  swiper = null;

  initSwiper(selector) {
    this.swiper = new Swiper(selector, {
      pagination: '.home-swiper-pagination',
      speed: 400,
      spaceBetween: 100,
      nextButton: '.swiper-button-next',
      prevButton: '.swiper-button-prev'
    });
  }

  goTo(index) {
    this.swiper.slideTo(index);
  }
}

And use it into your @Page

@Page({
  templateUrl: 'build/pages/home/home.html',
  providers: [HomeSwiper]
})
export class Home {
  constructor(private swiperService: HomeSwiper) {
    this.swiperService.initSwiper('.home-modal-swiper-container');
  }

  skipSlides() {
    this.swiperService.goTo(indexOfTheLastSlide);
  }
}