Add animated SVG to Angular

You might be reading this because you've animated you first SVG and tried to import it into an Angular project, just like you would import a regular SVG, but even though the SVG loads, it doesn't animate.

That's because Angular needs to load the SVG and JavaScript separately. SVGator conveniently bundles the SVG and the JavaScript together, so you don't have to deal with multiple files at the same time. While this works for most use cases, it doesn't work for Angular.

We also have an example app on github, that's basically an Angular app with an animated SVG on the home page.

Step 1

Let's start by exporting the SVG.

Go to svgator.com,  export the animated SVG with JavaScript as the animation type and the player option as external.

Step 2

Create a component for the SVG.

Now you can add the SVG to this component.

We will start with the SVG part. This is usually at the beginning of the file, it starts with an <svg> tag and it ends right before the <script> tag.

In VS Code, you can quickly search for these tags using ctrl+ f .

Copy the selected SVG and paste in the new component file that we created earlier.

After you pasted it, make sure you added the </svg> tag to the end of the copied code.

Step 3

Now it's time to add the JavaScript that resides between the <script> and </script> tags.

Copy this part .

Go to the SVG template:

  • Create a OnInit Lifecycle and paste the code inside, like this:
import {OnInit, Component} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']

})
export class AppComponent implements OnInit{
  title = 'project';
  ngOnInit(): void {
    // @ts-ignore
      (function(s,i,u,o,w, .....(svg javascript part)
      }
}

And that's all. Your SVG should work now.

If it doesn't work or you get stuck, try our github example.


Still got questions? Send us an email to contact@svgator.com and we will get back to you as soon as we can.