Reputation: 1
I'm using Swiper in my app with Angular 14, Ionic 6.5 and Swiper 11. After defining and assigning properties to my swiper-container
and slides, i noticed that when entering the page, the swiper doesn't initialize automatically -- or at least not fully.
Properties like loop, pagination, effect seems to work correctly, but the slides don't autoplay automatically until i manually move one slide, or sometimes after some time has passed.
Note: The array is not asynchronous, is defined in my TS.
HTML:
<swiper-slide *ngFor="let img of slider" style="display: flex; align-items: flex-start;">
<img [src]="img.img" alt="" style="width: 100%; height: 100%; object-fit: cover;">
<ion-grid style="padding-top: 65px;">
<div style="padding: 5px 10px 15px 10px; text-align: center;">
<ion-text style="color: white;
font-size: 31px;
font-style: italic;
font-weight: 600;
text-align: center;
">
{{ img.title }}
</ion-text>
</div>
</ion-grid>
</swiper-slide>
</swiper-container>
TypeScript:
getSwiperParams() {
return {
loop: true,
pagination: {
type: "progressbar"
},
effect: "fade",
autoplay: {
delay: 3000,
disableOnInteraction: false
}
};
}
initializeSwiper() {
const swiperEl = this.swiperContainer?.nativeElement;
if (!swiperEl) return;
const swiperParams = this.getSwiperParams();
Object.assign(swiperEl, swiperParams);
swiperEl.initialize();
}
and initializeSwiper()
is called on my ngAfterViewInit()
which I thought would be the correct lifecycle hook for this initialization. However, it seems that at this point the swiper is not "fully" ready to initialize.
I tested adding a button on my HTML which calls initializeSwiper()
and after clicking it, Swiper starts autoplaying correctly. This indicated to me that the issue might be related to timing.
I then tried using the Ionic lifecycle hook IonViewDidEnter()
and voilá, it worked correctly, initializing and autoplaying the slides as expected.
What is the correct way and the correct lifecycle moment to initialize Swiper?
I thought ngAfterviewInit
was the correct timing to call this initialization, but seems like in my case it didn't work correctly. Is this behavior related to Ionic's lifecycle?
Thanks for your time reading this.
Upvotes: 0
Views: 39