EddyG
EddyG

Reputation: 2129

ngx-slick-carousel reinitialize slick after unslick in Angular

I am using Angular 7. I added ngx-slick-carousel as described here: https://www.npmjs.com/package/ngx-slick-carousel.

I adjusted slideConfig the way I want:

slideConfig = {
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 1000,
    speed: 1400,
    infinite: true,
    lazyLoad: "ondemand",
    responsive: [
      {
        breakpoint: 991,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 2,
          autoplaySpeed: 2000,
          speed: 100
        }
      }, 
      {
        breakpoint: 575,
        settings: unslick
      }
    ]
  }; 

I want to unslick on viewport less than 575px so I added this in slideConfig. Configuration parameters are explained here: https://kenwheeler.github.io/slick/

Now, if viewport gets back greater than 575px I want to re-activate the slick.

None of the solutions provided online worked.

Here for example, when I created the ViewChild, console prints undefined. Reference slick instance from component (ngx-slick-carousel)

I referred also to solutions where jQuery is used to enabled slick again, but the jQuery functions are not identified in Angular. https://github.com/kenwheeler/slick/issues/1730

Upvotes: 0

Views: 5663

Answers (1)

EddyG
EddyG

Reputation: 2129

The slick carousel element in html has a property #slickModal="slick-carousel".

In our component, we import the SlickCarouselComponent

import { SlickCarouselComponent } from "ngx-slick-carousel";

and refer to the slick carousel in a variable

@ViewChild("slickModal") slickModal: SlickCarouselComponent;

now we import the HostListener

import { HostListener } from "@angular/core";

and in the following function, we detect the width of the viewport. If the viewport is greater than the unslick breakpoint, we re-initialize the slick.

@HostListener("window:resize", ["$event"])
getScreenSize(event?) {
  if (this.slickModal !== undefined) {
     if (window.innerWidth > 575) {
       if (!this.slickModal.initialized) {
         this.slickModal.initSlick();
       }
     } else if (this.slickModal.initialized) {
       this.slickModal.unslick();
     }
  }
}

make sure to call this function in the constructor of your component

constructor() {
    this.getScreenSize();
}

Upvotes: 1

Related Questions