spartacus-storefront

How can auto play carousel in SAP/spartacus?


I am using carousel components of SAP/spartacus. My requirement is carousel should be auto play. Please help me to resolve it.


Solution

  • As I can see in the source code it's not implemented OOTB in Spartacus, but you can easily add this functionality to your project.

    Please create your own CarouselComponent, based on Spartacus' one.

    1 class should implement also OnDestroy interface

    2 add new dependency protected ref: ChangeDetectorRef

    3 add new property subscription = new Subscription();

    4 fill method ngOnInit by this:

        super.ngOnInit();
        this.subscription = this.size$
          .pipe(
            take(1),
            switchMap((size) =>
              interval(5000).pipe(
                tap(() => {
                  this.activeSlide =
                    this.activeSlide > this.items.length - size - 1
                      ? 0
                      : this.activeSlide + size;
                  this.ref.markForCheck();
                })
              )
            )
          )
          .subscribe();
    

    5 remember about ngOnDestroy() { this.subscription.unsubscribe(); }


    Then prepare your own version of BannerCarouselComponent (change the only template - use your new carousel component instead cx-carousel)

    At the end, set:

          cmsComponents: {
            RotatingImagesComponent: {
              component: YourBannerCarouselComponent,
            },
          },