javascriptangularparticles.js

How to import and use particles.js in an Angular/Angular2/Angular4 app


I have an Angular app that I want to use particles.js in however I have no clue how to add it and get it working.

I've added it to the .angular-cli.json

  "scripts": [
    "../node_modules/particles.js/particles.js"
  ],

And I've imported it into my component

import * as  particlesJS from 'particles.js';

And attempted to initialize it using

  particlesJS.load('particles-js', 'assets/particles.json', function() {
    console.log('callback - particles.js config loaded');
  });

Has anyone got this working?


Solution

  • Here is how to do that:

    1. Just import the particles.js in your index.html (cdn or local)

      <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
      
    2. Put in the div anchor into your component template (you could also put it to index.html or somewhere else)

      <div id="particles-js"></div>
      
    3. Make the package visible by adding a simple type definition (in your component or in the typings.d.ts)

      declare var particlesJS: any;
      
    4. Initialize it in ngOnInit (or somewhere else)

      particlesJS.load('particles-js', 'particles.json', null);
      

    I have made a little plunker example: http://plnkr.co/edit/GLRvYgNPJue4KqdMuAJB?p=preview