Sufail Kalathil
Sufail Kalathil

Reputation: 647

Swiper not working after http request in angular

I'm using angular 9 for my project and I need to use swiper. But I got a problem when using *ngFor.Swiper is working without HTTP call. If I use HTTP call , then the swiper won't work.

Html

<swiper
                    #swiperRef
                    [slidesPerView]="1"
                    [spaceBetween]="50"
                    (swiper)="onSwiper($event)"
                    [breakpoints]="breakpoints"
                    [scrollbar]="scrollbar"
                    [loop]="true"
                    (observerUpdate)="onSwiper($event)"
                    [pagination]="{ el: '.swiper-pagination.pagination-test' }"
                >
                    <ng-template
                            swiperSlide
                            let-data
                            *ngFor="let slide of httpData; index as I"
                    >
                        <p>swiper</p>
                    </ng-template>
                    <div slot="container-end" class="swiper-pagination pagination-test"></div>
                </swiper>

TS

httpData=[];
ngOnInit(){
    httpClient.subscribe(res=>{
    httpData=res
    })
}

slides = Array.from({ length: 5 }).map((el, index) => `Slide ${index + 1}`);

No issue found when I use slides instead of httpData.Error occurred when I use httpData for iteration

                        <ng-template
                                swiperSlide
                                let-data
                                *ngFor="let slide of slides; index as I"
                        >
                            <p>swiper</p>
                        </ng-template>

Upvotes: 0

Views: 509

Answers (1)

Jean Carlo Lo Iacono
Jean Carlo Lo Iacono

Reputation: 47

I had the same problem, I was making some httpClient requests with Angular and of course this request is asynchronous, what actually happens, it loads the first slider of the request and then continues loading the rest of the page (behind swiper keeps making the requests) and these are loaded at the end of the page, but the dom already generated the view.

This causes errors in the scrolling controls, to work correctly, they require that:

  • Initialize them when they are visible
  • Update them when they are visible

You will have to enable the observer parameters in your case #swiperRef

observer: true observeParents: true

I'm sure this will solve your problem.

Upvotes: 2

Related Questions