How to fix autoplay issue when rotate in ionic4?

I have used ion-slides in my project. The code is given below:

<ion-grid class="ion-margin-left">
    <ion-slides [options]="slideConfig">
        <ion-slide *ngFor="let item of items">
            <ion-card style="margin-right: 2px">
                <div class="img-container">
                    <img src="/assets/contents/gif_icon/{{item.imgName}}" class="img-style">
                </div>
                <ion-card-content>
                    <p>{{item.title}}</p>
                </ion-card-content>
            </ion-card>
        </ion-slide>
    </ion-slides>
</ion-grid>

The slide was working perfectly before using slideConfig options autoplay: true. The slide configuration options code is given below.

this.slideConfig = {
   slidesPerView: window.innerWidth / 140,
   autoplay: true
};
  @HostListener('window:resize', ['$event'])
  onResize(event) {

  this.slideConfig = {
    slidesPerView: window.innerWidth / 140,
    autoplay: true
  };
}

The problem mainly occurs when I rotate the screen. I am trying to show cards which width will be 120px. And which will be always 120px even after rotating? Before rotating the card was slide normally but after rotate the card was sliding too fast. So How can I fix this issue?

Please, Note one thing, Whenever I rotate the slidesPerView will be dynamic. For example, in the portrait mode slidesPerView might be 3 for a device. For the same device if the user rotates the device then slidesPerView might be 5. To achieve this I have used @HostListener('window: resize') function. But if I load the project in portrait mode then if I rotate the device then autoplay slide a little bit fast. I know the problem was occurring because of slidesPerView is dynamic. But I cannot fixed the slidesPerView and at the same time, the slide needs to be autoplay. How can I achieve this?

Upvotes: 0

Views: 339

Answers (1)

Khanh Le Tran
Khanh Le Tran

Reputation: 900

Try this:

Component.ts

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  @ViewChild('slides',null) slides: IonSlides;

  slideOpts = {
    slidesPerView: 1,
    autoplay: true,
    speed: 600,
    slidesPerColumn: 'auto'
  };

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    setTimeout(() => this.slides.update(), 100); 
  }
  constructor() { }

}

HTML

<ion-slides pager="true" [options]="slideOpts" #slides>
</ion-slides>

You can change the speed to run faster or slower if you want with property speed in option.

Upvotes: 1

Related Questions