How can I add infinite scrolling to this Angular carousel?

前端 未结 1 1503
盖世英雄少女心
盖世英雄少女心 2020-12-22 05:54

I followed this fantastic article, that demonstrates how to make a simple carousel with the use of two directives and one component in Angular.

The feature set is ve

相关标签:
1条回答
  • 2020-12-22 06:27

    Updated (before I reorder the queryList when we are in the last but one and in the second slider)

    there're a work-around. The key is reorder the QueryList and change the currentSlide when you're in the last (before make a next) or the first one (before make a prev)

    First change the function transitionCarrousel to allow an "animate" in 0 seconds

      private buildAnimation(offset, time: any) {
        return this.builder.build([
          animate(time == null ? this.timing : 0, 
              style({ transform: `translateX(-${offset}px)` }))
        ]);
      }
    

    The functions next and prev becomes like

    next() {
        //if we are in the last 
        if (this.currentSlide + 1 == this.items.length) {
          //reorder the QueryList, 
          let arr = this.items.toArray();
          let first = arr.shift();  //remove the first element
          arr = arr.concat([first]);  //Concat at last of the array
          this.items.reset(arr);
          this.currentSlide--;  //less currentSlide
          this.transitionCarousel(0); //execute the animation in 0 seconds
        }
        this.currentSlide = (this.currentSlide + 1) % this.items.length;
        this.transitionCarousel(null);
      }
    
      prev() {
        //If we are in the first one
        if (this.currentSlide  == 0) {
          let arr = this.items.toArray();
          let last = arr.pop();  //remove the last element
          arr = [last].concat(arr); //create an array with the last element+arr
          this.items.reset(arr);
          this.currentSlide++;  //change the currentSlide
          this.transitionCarousel(0);  //execute the animation in 0 seconds
        }
        this.currentSlide =
          (this.currentSlide - 1 + this.items.length) % this.items.length;
        this.transitionCarousel(null);
      }
    

    You can see work in the stackblitz

    0 讨论(0)
提交回复
热议问题