Search code examples
javascriptcssangularflickity

Why are flickity css not being loaded in Angular?


So I am trying to incorporate flickity carousel in my Angular app. I think technically it should working fine, the issue that stops it from making it work the way it should is that none of the css from flickity.css seems to be loading. I was hoping someone might have an idea why that might be the case.

I added flickity to my app by running npm install flickity.

Thereafter, in my component, i added flickity as such:

import * as flickity from 'flickity';

Next I initialised everthing:

  ngOnInit() {
    window.addEventListener("DOMContentLoaded", function() {
      this.carousel = document.querySelector('.container');
      console.log(this.carousel);
      this.flick = new flickity(this.carousel, {
        imagesLoaded: true,
        wrapAround: true
      });

      var imgs = this.carousel.querySelectorAll('.item img');
      console.log(imgs);
      var docStyle = document.documentElement.style;
      var transformProp = typeof docStyle.transform == 'string' ?
        'transform' : 'WebkitTransform';

      this.flick.on('scroll', function() {
        this.flick.slides.forEach(function(slide, i) {
          var img = imgs[i];
          var x = (slide.target + this.flick.x) * -1 / 3;
          img.style[transformProp] = 'translateX(' + x + 'px)';
        });
      });
    });
  }

Essentially all the js seems to be working fine but none of the inherent flickity is being rendered, meaning everything from the flickity viewport, buttons etc.. hence the whole thing won't working.


Solution

  • You need to add the flickity css file to your angular.json imports like so

    angular.json

    // ...
    "styles": [
     // path to flickity css
     // I just made this up so you will have to double check the path to the css file
     "node_modules/flickity/dist/flickity.min.css"
    ]
    

    Please note: You will have to restart your project once this has been added for changes to take effect.

    OR

    As per the flickity docs you could just include this

    <link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">
    

    in your index.html