在使用 Angular swiperJS 的时候,需要注意的是,在将 initialSlide 设置为非零值时,slideChange 事件可能无法正常工作。这是因为 slideChange 事件会在组件初始化后被触发,在初始化完成之前,事件可能会被忽略。因此,我们需要使用一个延迟器来确保组件初始化完成后再触发 slideChange 事件。
具体方法是在组件的 ngAfterViewInit 生命周期中添加一个延迟器,等待组件初始化完成后再触发 slideChange 事件。示例代码如下:
import { Component, ViewChild } from '@angular/core'; import { SwiperComponent } from 'swiper/angular';
@Component({
selector: 'my-component',
template:
})
export class MyComponent {
@ViewChild(SwiperComponent, { static: false }) swiper: SwiperComponent;
ngAfterViewInit() { setTimeout(() => { this.swiper.update(); this.onSlideChange(); }, 0); }
onSlideChange() { console.log('Slide changed!'); } }
在上述例子中,我们在组件的 ngAfterViewInit 生命周期中添加了一个延迟器,在延迟器中调用 update() 方法来确保 Swiper 的初始化完成,然后再手动触发 slideChange 事件。
参考链接:
https://github.com/nolimits4web/swiper/issues/3734
https://stackoverflow.com/questions/61770794/angular-swiperjs-slidechange-event-does-not-work-when-initializing-initialslid