I have an Issue with the carousel that I am creating because the items are repeated after changing the size of the screen. My code base comes from the answer given by Eliseo in this Stackoverflow question where his carousel has the functionality to show/hide the arrow functions after changing the variable noCarousel
based on the dimensions of the user’s screen and the amount of items to show, this functionality presents the detail that after hiding the arrows the items are doubled and/or tripled
Code in Stackblitz:
https://stackblitz.com/edit/angular-1vnbxc-zc9fz8?file=src/app/app.component.html
Steps to recreate the Issue (2 ways):
- If when opening the code in Stackblitz the carousel has the functionality of the active arrows, expand the sample screen until the arrows disappear.
- If when opening the code in Stackblitz the carousel has the inactive arrows functionality, collapse the sample screen until the arrows are activated and then expand it until the arrows disappear.
Advertisement
Answer
it’s a bit complex, the carousel duplicate the images to allow show a bit in both sides when the size is less than the whole size.
The solution is store in an array the “duplicated templates”
Declare an empty array
added:EmbeddedViewRef<any>[]=[]
And, when add a “template” use push to add to the array and if “noCarousel” remove it
private resizeCarousel() { if (this.carousel) { let totalWidth = this.carousel.nativeElement.getBoundingClientRect().width; if (totalWidth > this.slides.length * this.slideWidth) { .... this.noCarousel = true; this.added.forEach(x=>x.destroy()) return; } this.noCarousel = false; ... this.slides.last.viewContainer.createEmbeddedView( this.slides.last.templateRef ); this.slides.forEach((x, index) => { if (index && index >= this.slides.length - this.increment - count) { this.added.push( this.slides.first.viewContainer.createEmbeddedView(x.templateRef) ); } if (index < this.increment + count) { this.added.push( this.slides.last.viewContainer.createEmbeddedView(x.templateRef) ); } }); if (this.increment + 1 >= this.slides.length) { this.added.push( this.slides.first.viewContainer.createEmbeddedView( this.slides.first.templateRef, null, 0 ) ); } this.slides.first.viewContainer.createEmbeddedView( this.slides.first.templateRef ); this.currentSlide = 0; this.transitionCarousel(0, this.currentSlide); }
I forked your stackblitz here
NOTE: Really is a bit old stackblitz, I’m not prety sure if it’s the best solution to make a carousel (If I have a time, I’ll try to checked more)