问题描述
我有一个仅当元素位于滑块中心时才需要调用的函数。我怎样才能做到这一点?
我的 HTML 是:
<owl-carousel-o [options]="customOptions">
<ng-container *ngFor="let slide of slides">
<ng-template carouselSlide [id]="slide.id">
<img [src]="slide.img" (swipeup)="startAnimation('swipeup',$event)">
</ng-template>
</ng-container>
</owl-carousel-o>
我的自定义选项是:
customOptions: OwlOptions = {
loop: false,center: true,dots: false,nav: false,responsive: {
0: {
items: 3
},400: {
items: 2
},740: {
items: 3
},940: {
items: 4
}
}
}
仅当图像居中时才需要调用函数 startAnimation()
。
我对 Angular 还很陌生。任何帮助将不胜感激。
解决方法
你可以附加一个守卫,这样如果你的元素的索引不等于slides.length
的中间元素,它就不会执行其余的
<ng-container *ngFor="let slide of slides; let i = index"> <!-- get index here -->
<ng-template carouselSlide [id]="slide.id">
<img [src]="slide.img" (swipeup)="startAnimation('swipeup',$event,i,slides.length)"> <!-- pass index and length here -->
</ng-template>
</ng-container>
startAnimation('swipeup',index,slidesLength) {
if(index !== (Math.floor((slidesLength- 1) / 2))) {
return;
}
}