Home > Software engineering >  Flickity carousel doesn't work if used (ngfor)
Flickity carousel doesn't work if used (ngfor)

Time:06-22

I'm using a carousel called flickity

when I'm using static data the carousel works normally

  • normal behavior code:

    <div  data-flickity='{"autoPlay": "10000", "wrapAround": true, "imagesLoaded": true}'>
      <a href="">
        <img 
          src="https://149634564.v2.pressablecdn.com/wp-content/uploads/2021/08/rober-gonzalez-ShXbeohihGo-unsplash-800x550.jpg"
          alt="">
      </a>
    
      <a href="">
        <img 
          src="https://149634564.v2.pressablecdn.com/wp-content/uploads/2021/08/niklas-veenhuis-TEjATSCI2A4-unsplash-800x550.jpg"
          alt="">
      </a>
    </div>
    

but when I request data then use *ngfor it shows all slides as one block, no sliding.

  • not working code:

      <div  #carousel
    data-flickity='{"autoPlay": "10000", "wrapAround": true, "imagesLoaded": true}'>
    
    <a href="" *ngFor="let show of RecentReleases">
      <img  [src]="show.largePoster" alt="poster">
    </a> </div>
    
  • my ts code:

    RecentReleases?: IShow[];
    
    ngOnInit(): void {
      this.homeService.getRecentReleases().subscribe((shows) => {
        this.RecentReleases = shows;
      });
    }
    

Does anyone know how to solve this?

-Edit 1: when I initialized the "RecentRleleases" with a static data it worked correctly so I think the problem in waiting the data ?

CodePudding user response:

Not sure but I think the code should be:

<div *ngIf="RecentReleases?.length > 0"  data-flickity='{"autoPlay": "10000", "wrapAround": true, "imagesLoaded": true}'>
  <a href="" *ngFor="let show of RecentReleases">
    <img 
      [src]="show.largePoster"
      alt="">
  </a>
</div>

in order to reproduce the "normal behavior code"

CodePudding user response:

The problem is that when you try to create the carousel, the elements are not in the screen. As Zerotwelve say you need initialize using javascript. Where? in subscribe function and enclosed in a setTimeout to give time to Angular to repaint the elements

ngOnInit(): void {
  this.homeService.getRecentReleases().subscribe((shows) => {
    this.RecentReleases = shows;
    setTimeout(()=>{
       const flkty = new Flickity( '.main-carousel', {
      // options
        cellAlign: 'left',
        contain: true
      });

    })
  });
}
  • Related