Angular: Adding Google Analytics (External Script)

Joshua
6 min readJul 27, 2020

--

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.

Setup

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:

New Format:

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.

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.

Test

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 on to learn how.

Capturing Interaction

Google Analytics was designed to provide insights on user experience based on user interactions. It is not so much an Application Performance Monitor (APM) like Application Insights or New Relic (while it can provide some extremely basic insights), but rather to assist internal teams with increasing conversion rates and improving customer acquisition (and retention). To this end, we may want to add some basic interactions to our Google Analytics metrics. In this post, we’re not going to cover goal setting, funnels, metrics, etc. We’re simply going to track a few events. However, the following principles can be used to accomplish the same purpose.

Create a Button

On my application’s First Page (that I created in my “Setup” on page 1 of this post). I’ve created a simple button, and I bound it to a click event.

<button (click)="click()">Click Me!</button>

View the source here.

In my page’s TypeScript file, I’ve created a click function. Depending on whether you are using the legacy analytics code or the new code, your method will call a different Google Analytics function.

Legacy Format:

New Format:

You can find the source here.

Essentially, both code samples accomplish the same thing; namely, they register an event with Google Analytics. The only call-out here is line 3 (for both versions). In each version, depending on which library we are using, we declare a variable (e.g. ga or gtag) outside the scope of the component. This is to prevent compilation errors from the TypeScript compiler.

(NOTE: One downside of using Google Analytics is that the values for a specific event are summed in the daily reports. So, if the button on the page is clicked 3 times, the final event report will show 6 (1 for the first click + 2 for the second + 3 for the third) for the value. If you want to track values for individual users, sessions, clicks, etc., then you’ll need to configure metrics in Google Analytics.)

With your click event wired up, go ahead and run your application again (remember, with the --prod flag). You’ll then begin to see events being logged in realtime on your Google Analytics dashboard.

Conclusion

We’ve just added Google Analytics to our Angular application by utilizing an external JavaScript file. There is a better, “more Angular” way to do this via services (which we’ll cover in the next post). However, this approach is great for the quick, simple addition of Google Analytics to a new project, or to add Google Analytics to a pre-existing project where the return on injecting Google Analytics as a service isn’t really worth the investment of time.

Personally, I only use Google Analytics for tracking page views. That’s it. For other metrics, such as application performance and user interaction, I use a formal APM (such as Application Insights or New Relic).

Again, for the full source code to this project, check out my GitHub blog demos repository.

Originally published at http://jdav.is on July 27, 2020.

--

--

Joshua

Azure Global Cloud Solutions Architect for Microsoft, passionate enterprise software developer, lover of Jesus Christ.