Angular9中HTTP请求后*ngFor渲染的Swiper无法工作如何解决
问题原因
该问题核心是Swiper组件的初始化时机早于HTTP请求返回数据的时机:
- 静态数组在组件初始化阶段就已完成赋值,Swiper初始化时可正常识别所有轮播项
- httpData初始为空数组,Swiper初始化时未检测到有效轮播项,后续接口返回数据赋值后,Swiper默认不会主动重新扫描DOM结构更新配置,因此出现失效问题
解决方案
你可以选择以下任意一种方案解决:
方案1:控制Swiper渲染时机(最推荐,实现最简单)
等接口数据返回后再渲染Swiper组件,保证Swiper初始化时轮播项已全部存在,效果和使用静态数组完全一致。
修改HTML代码,给swiper组件添加*ngIf判断:
<swiper *ngIf="httpData.length" #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>
方案2:数据返回后手动调用Swiper更新方法
先在TS中获取swiper实例引用,接口数据赋值完成后手动触发Swiper更新。
修改TS代码:
import { ViewChild } from '@angular/core'; // ...其他依赖引入 httpData=[]; // 获取swiper组件引用 @ViewChild('swiperRef') swiperRef: any; ngOnInit(){ httpClient.subscribe(res=>{ this.httpData = res; // 等待Angular完成DOM渲染后触发Swiper更新 setTimeout(() => { if(this.swiperRef?.swiperInstance) { const swiper = this.swiperRef.swiperInstance; // 更新轮播项配置 swiper.updateSlides(); // 刷新Swiper全局配置 swiper.update(); // 同步更新分页器 swiper.pagination?.update(); // 开启loop的情况下可调用重新初始化loop逻辑 swiper.loopCreate?.(); swiper.slideTo(0, 0); } }, 0) }) } slides = Array.from({ length: 5 }).map((el, index) => `Slide ${index + 1}`);
方案3:开启Swiper自动DOM监听
开启Swiper内置的DOM监听器,自动感知轮播项的新增/删除变化并自动更新。
修改HTML代码,给swiper组件添加监听器配置:
<swiper #swiperRef [slidesPerView]="1" [spaceBetween]="50" (swiper)="onSwiper($event)" [breakpoints]="breakpoints" [scrollbar]="scrollbar" [loop]="true" [observer]="true" [observeParents]="true" [observeSlideChildren]="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>
内容的提问来源于stack exchange,提问作者Sufail Kalathil
相关产品推荐
相关产品推荐

