Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ionic3 multiple swiper sliders on samepage

I am using ionic 3 while placing 3 swiper sliders on same page i am unable to control their behavior separately i am bit new for angular js as well ts and ionic

here is code

<ion-slides style="height: 30%;" pager>
  <ion-slide style="background-color: green" *ngFor="let post of posts">
    <h1>{{post.title}}</h1>
    <img [src]="post.image" />
  </ion-slide>
</ion-slides>


<ion-slides style="height: 30%;" pager>
  <ion-slide style="background-color: green" *ngFor="let post of posts">
    <h1>{{post.title}}</h1>
    <img [src]="post.image" />
  </ion-slide>
</ion-slides>

ts is

 @ViewChild(Slides) slides: Slides;

  goToSlide() {
    this.slides.slideTo(2, 500);

  }

   ngAfterViewInit() {
    //this.slides.freeMode = true;
    this.slides .slidesPerView=3,
    this.slides.spaceBetween=5;
    //this.slides.loop=true;
  }
like image 456
Amit Kumar Pawar Avatar asked Jul 03 '17 12:07

Amit Kumar Pawar


1 Answers

Instead of ViewChild, you can use ViewChildren to get all the instances of the slider in that page (Angular docs). Please take a look at this working plunker. The end result would be something like this:

Slider demo

Like you can see in the plunker, we get all the instances of the slider, and then we just get the target instance by using its index:

import { Component, ViewChildren, QueryList } from '@angular/core';
import { NavController, Content, Slides } from 'ionic-angular';

@Component({...})
export class HomePage {
  @ViewChildren(Slides) slides: QueryList<Slides>;

  constructor() {}

  public move(index: number): void {
    this.slides.toArray()[index].slideNext(500);
  }      

}

An then in the view:

<ion-header>
  <ion-navbar>
    <ion-title>Ionic Demo</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <ion-slides style="height: 75px" pager>
    <ion-slide><h1>Slide 1</h1></ion-slide>
    <ion-slide><h1>Slide 2</h1></ion-slide>
    <ion-slide><h1>Slide 3</h1></ion-slide>
  </ion-slides>

  <ion-slides style="height: 75px" pager>
    <ion-slide><h1>Slide 1</h1></ion-slide>
    <ion-slide><h1>Slide 2</h1></ion-slide>
    <ion-slide><h1>Slide 3</h1></ion-slide>
  </ion-slides>

  <ion-slides style="height: 75px" pager>
    <ion-slide><h1>Slide 1</h1></ion-slide>
    <ion-slide><h1>Slide 2</h1></ion-slide>
    <ion-slide><h1>Slide 3</h1></ion-slide>
  </ion-slides>

  <ion-row>
    <ion-col>
      <button (click)="move(0)" ion-button text-only>Move First</button>
    </ion-col>
    <ion-col>
      <button (click)="move(1)" ion-button text-only>Move Second</button>
    </ion-col>
    <ion-col>
      <button (click)="move(2)" ion-button text-only>Move Third</button>
    </ion-col>
  </ion-row>

</ion-content>
like image 76
sebaferreras Avatar answered Oct 10 '22 20:10

sebaferreras