Google Analytics is a fantastic resource when attempting to capture basic visitor behavior in your Angular application. To utilize Google Analytics, you will need to add the tracking script to your application’s source. Angular provides a few different mechanisms to accomplish this. The first approach it to save the tracking script to an external JavaScript file and include the file into your bundle for production releases. This approach is what the following blog post attempts to demonstrate.

As stated, there are a few approaches to including the Google Analytics code in your Angular application. This post will focus on levering a plain, external JavaScript file. The next post demonstrates how to include Google Analytics as an Angular service. All source code for this post can be found in my demo GitHub repository. Finally, this post assumes you understand how to use the Angular CLI.


Let’s begin by creating a few things:

  1. A new Angular application.
    The demo application is using CLI version 8.3.29, but you can use whichever version you prefer. I’ve also chosen to use SCSS for my styles, but, again, choose what you prefer. Finally, make sure you enable routing. Enabling routing will help with requests and can be utilized for things like setting the page titles through routing properties.
  2. Create a few pages.
    For the demo application, I’ve created 3 pages – Home, First Page, and Second Page. Additionally, on my first and second pages, I’ve added some buttons that bind to click events. This will allow us to interact with Google Analytics’s API for tracking customer interactions.
  3. Create a Google Analytics account along with a site.

Google Analytics

When creating a Google Analytics account, you will be presented with two options (formats) for the tracking code – the legacy format (using the ga method) and the newer format (gtag). Examples of each are below. (NOTE: The UA-XXXXXXXXX-1 code below will be different for your site. I’ve kept my demo code in the source for your reference.) In my repository, I’ve included both formats, but have commented out the legacy and the original, new format (see below for modifications).

Legacy Format:

    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
ga('create', 'UA-173474946-1', 'auto');
ga('send', 'pageview');

New Format:

<script async src=""></script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-173474946-1');

Whichever format you choose is entirely your decision. For a site that is being migrated or upgraded and already have Google Analytics enabled, you’ll need to confirm which format it’s currently using (NOTE: It appears that the ga method works with the newer format too, but I cannot guarantee complete compatibility nor any point(s) of deprecation).

Saving the Tracking Code

Once you’ve copied the code of your choice, you will need to save that code to a file for bundle injection.

Within the default Angular folder structure, there exists the folder src/assets. Create a new folder inside assets called scripts, and create a new file called google-analytics.js. (HINT: The new folder structure should appear as src/assets/scripts/google-analytics.js.) Paste your copied tracking code into this file and save it.

JavaScript Modification

Because the legacy format uses “pure” JavaScript, it can be copied and pasted as-is. Unfortunately, the new format will require a few changes so that it can be “injected” properly by the Angular application after bundling.

The modification will utilize JavaScript Promises for 1) creating the JavaScript script element; and, 2) adding the gtag method calls. Comparing to the original code above, see the necessary modifications below.

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

    new Promise((resolve) => {
        var script = document.createElement('script');
        script.src = "";
        script.async = true;
    new Promise((resolve) => {
        gtag('js', new Date());
        gtag('config', 'UA-173474946-1');

Because we aren’t adding the JavaScript to our application’s index.html and, instead, bundling it, we must wait for the Angular application to build and render the page. Once the page has rendered, the two JavaScript Promises will execute. The first Promise appends the Google Tag Manager script to the page’s body element, and then loads it asynchronously. Once complete, the Promise resolves and calls the gtag method. The second gtag method (highlighted) is what registers a page view with Google Analytics.

Including with the Bundle

There’s one last step to adding the JavaScript code to your application and that’s telling the CLI (WebPack) to package the analytics code with the compiled bundles.

One thing to note, we don’t want to track page views while the application is under development (local developer machines, shared development/QA environments, UAT, etc.). We only want to track page views when the application is pushed to production. The Angular CLI configuration file allows us to accomplish this very easily.

In the application’s top folder, locate the angular.json file and open it. On line (approximately) 36, you’ll see the JSON node "production". At the end of this node, you will see a "scripts" node defining an array. (NOTE: Your array may be empty or contain elements depending on whether you are working with a new application or an application already under active development.) Add your Google Analytics script file’s path (e.g. "src/assets/scripts/google-analytics.js") to the array. You can refer to the demo in GitHub for assistance.


At this point, your application should be ready for testing page views.

While under development, you are typically viewing/testing application changes by executing the command ng serve. However, remember, the Google Analytics code is only included when you specify the production build configuration.  Therefore, to test the Google Analytics in your development environment, you will need to include the --prod flag (e.g. ng serve --prod).

Once the application is running (with the production configuration loaded), begin navigating throughout your pages while checking your Google Analytics dashboard. You should see that you have one (or two) realtime visitor(s).

Now that Google Analytics has successfully been added to the application, you may want to track some basic user interactions. Continue to the next page to learn how.