SomebodyOnEarth
SomebodyOnEarth

Reputation: 418

Refresh HTML Component on window size change

I want to change the slidesToShow and slidesToScroll variables after the window size changes. I've tried using a @HostListener to detect when the window size changes but the ngx-slick component doesn't update after those variables are changed.

.ts

@HostListener('window:resize', ['$event'])
onResize(event) {
  this.updateSlidesToShow(window.innerWidth);
}

updateSlidesToShow(width: number) {
  if (width < 576) {
    this.slideConfig.slidesToShow = 1;
    this.slideConfig.slidesToScroll = 1;
  } else {
    this.slideConfig.slidesToShow = 3;
    this.slideConfig.slidesToScroll = 3;
  }
}

slideConfig = {
  'slidesToShow': 3,
  'slidesToScroll': 3,
  'dots': true,
  'autoplay': true,
  'autoplaySpeed': 10000,
};

.html

<ngx-slick class="carousel" #slickModal="slick-modal" [config]="slideConfig">
  <div ngxSlickItem *ngFor="let slide of slides" class="slide" style="padding: 0 10px">
    <img src="{{ slide.img }}" alt="" width="100%">
  </div>
</ngx-slick>

Upvotes: 1

Views: 2232

Answers (1)

abdulrahman alaa
abdulrahman alaa

Reputation: 557

Due to a limitation in the ngx-slick because he expects the config object to be passed and angular will not run the change detection after changing any property in that object.

The config object passed to the component ngx-slick will not be reevaluated as angular do not know it's changed as it's not feeling that properties are affected.

The only workaround that I do suggest is recreating the component after changing the width of the screen as I implemented in the following demo https://stackblitz.com/edit/angular-fucgug

Upvotes: 2

Related Questions