angularangular2-directivesflickity

Flickity stops working the moment i use *NgFor


I am trying to use Flickity in an angular app that i am building. Here is the link I am also aware of the ngx-flickity but i do not want this as it isn't production ready.

This code below works

<div class="carousel">
    <div class="carousel-cell">...</div>
    <div class="carousel-cell">...</div>
    <div class="carousel-cell">...</div>
    ...
</div> 

The moment i use *NgFor, it stops working without any errors

<div class="carousel">
    <div class="carousel-cell" *ngFor="let product of products">
        {{ product.name }}
    </div>
</div>

I also tried the prepend method but it didn't work.


Solution

  • First of all, you are suing document.querySelector('.carousel') which will return only one element (the first one) in case you have multiple carousels elements it won't work for the others. Second, you want to instantiate the flick once you have the data returned and once they are rendered. A quick fix is to use this:

      ngOnInit(): void {
      this.dataService.getProducts().subscribe(products => {
          this.products = products;
          setTimeout( () => {
           document.querySelectorAll(".carousel").forEach(c => {
            let flick = new flickity(c, { cellAlign: "left", contain: true});
            })});
        });
      }
    

    UPDATE:

    a better solution than using setTimeout is to use the ChangeDetecrotRef to force change detection explicitly (rendering) right after receiving the data from the server.

    import { ChangeDetectorRef, Component, OnInit } from "@angular/core";
    ...
      constructor(private dataService: DataService, private cdr: ChangeDetectorRef) {}
    
      ngOnInit(): void {
      this.dataService.getProducts().subscribe(products => {
          this.products = products;
          this.cdr.detectChanges();
          document.querySelectorAll(".carousel").forEach(c => {
            let flick = new flickity(c, { cellAlign: "left", contain: true});
            });
        });
      }
    

    Demo