nolimits4web / swiper

Most modern mobile touch slider with hardware accelerated transitions
https://swiperjs.com
MIT License
40.07k stars 9.75k forks source link

Handle active index properly when dynamically prepending/lazy loading slides through the data array #7297

Open github-id01 opened 10 months ago

github-id01 commented 10 months ago

Discussed in https://github.com/nolimits4web/swiper/discussions/7287

Originally posted by **github-id01** January 31, 2024 Requirement: There are hundreds of slides that need to be displayed, so to handle the performance 3 slides are loaded at a time and the initially displayed slide is the 2nd/middle one. So intially when a user swipes to the 3rd slide, 3 more slides are appended at the end of the data array on which the slides are looped over via ngFor in the angular template. And in the same way if a user swipes to the left most 1st slide, then 3 more slides are prepended at the beginning of the data array. Issue: The issue is with the activeIndex, so let’s suppose 3 more slides are prepended like: ``` slideChange(swiper: any) { // the below code is called on condition if active index is 0, which means user is the at first slide so add more slides to it. const result = loadPreviousSlides() this.currentIndex = swiper.detail[0].activeIndex; this.textPages = [...result, ...this.textPages] this.swiper?.nativeElement.swiper.update() result.length && this.swiper.nativeElement.swiper.slideTo(result.length) } ``` Now when a user swipes to the first slide, the above function is called on swiperslidechange event, and based on a condition 3 more slides are prepended to the dataset. Now the issue arises when the user swipes to the first slide backwards, the activeIndex is 0. And when 3 more slides are prepended to it at that moment like in the above function, the total slides become 6, and in actual the currently display slide should be the 4th one, which was the 1st one before prepending more slides, and since before prepending more slides, the activeIndex was 0, so the swiper automatically swipes to the first slide when more slides are prepended to it, while in actual I want the activeIndex to be 3 so it stays on the actual slide rather than swiping back to the freshly added slides. So how can I handle or set the activeIndex to 3 or is there something else that could come in handy to handle this case ? slideTo works here, but that slides back to the original slide after the swiper is swiped to the 1st slide, so it gives a glitchy behaviour.
zhi-zhi-zhi commented 5 months ago

I meet the same question. also dynamically load. also unshift one item to the array.

but activeIndex still is zero. actually expected change to 1.

example: first slides: ['oldOne'] current activeIndex: 0

after unshift one new slides to array slides: ['unshiftOne', 'oldOne'] current activeIndex: 0❌ now display slide is 'oldOne' and now activeIndex is 0 but activeIndex should update to 1!!