每当您与轮播的一次调用交互时(即单击下一个或上一个),动画都会为组件的两个实例播放。这里出了什么问题?
carousel.component.ts
@Component({
selector: 'app-carousel',
standalone: true,
templateUrl: './carousel.component.html',
imports:[ CommonModule ],
styleUrls: ['./carousel.component.scss'],
animations: [ CarouselAnimation ]
})
export class CarouselComponent {
@Input() items: string[] = [];
@Input() itemsPerSlide: number = 0;
@Input() carouselName:string = "";
currentIndex: number = 0;
hasNextItems: boolean = true;
get groupedItems(): string[][] {
const result: string[][] = [];
for (let i = 0; i < this.items.length; i += this.itemsPerSlide) {
result.push(this.items.slice(i, i + this.itemsPerSlide));
}
return result;
}
next() {
const nextIndex = (this.currentIndex + 1) % this.groupedItems.length;
this.hasNextItems = this.groupedItems[nextIndex].length > 0;
if (this.hasNextItems) {
this.currentIndex = nextIndex;
}
}
prev() {
const prevIndex = (this.currentIndex - 1 + this.groupedItems.length) % this.groupedItems.length;
const prevItemsPerSlide = this.groupedItems[prevIndex].length;
if (prevItemsPerSlide > 0) {
this.hasNextItems = true;
this.currentIndex = (this.currentIndex - 1 + this.groupedItems.length) % this.groupedItems.length;
}
}
}
carousel.component.html
<div id="DynamicCarousel" class="carousel slide carousel-fade" data-ride="carousel">
<div class="carousel-inner">
<div *ngFor="let itemGroup of groupedItems; let i = index" [class.active]="i === currentIndex" class="carousel-item" [@fadeInOut]>
<div class="d-flex justify-content-around">
<div *ngFor="let item of itemGroup" class="carousel-inner-item">
<img class="d-block w-100" [src]="item" alt="Slide {{i + 1}}">
</div>
</div>
</div>
</div>
<a class="carousel-prev" href="#DynamicCarousel" role="button" data-slide="prev" (click)="prev()">
<div class="icon-container">
<i class="fa fa-solid fa-arrow-left"></i>
</div>
</a>
<a class="carousel-next" href="#DynamicCarousel" role="button" data-slide="next" (click)="next()">
<div class="icon-container">
<i class="fa fa-solid fa-arrow-right"></i>
</div>
</a>
</div>
使用方法
<h2>Carousel</h2>
<app-carousel [items]="carouselItems" [itemsPerSlide]="3" [carouselName]="'Carousel'"></app-carousel>
<h2>Carousel2</h2>
<app-carousel [items]="carouselItems2" [itemsPerSlide]="3" [carouselName]="'Carousel2'"></app-carousel>
您需要传递两个唯一的
carouselItems
实例,这将导致此问题。请确保属性carouselItems
和carouselItems2
都有自己独特的数组,您也可以使用实用函数来进行克隆!
import { cloneDeep } from 'lodash'
或
const cloneArray = JSON.parse(JSON.stringify(originalArray));
由于数组是通过引用存储的,这只是对内存位置的引用,因此一个组件的更新将会对使用相同引用数组的所有相关组件产生副作用,除非它被克隆!