As stated in the previous post, Google Analytics is a fantastic resource when attempting to capture basic behavior from your Angular application’s users. To leverage Google Analytics, you’ll need to add the tracking script to your application’s source. The previous post demonstrated how to add Google Analytics to your Angular application by bundling an external JavaScript file with your production build. The second approach for adding Google Analytics is to inject the required scripts as a service. The following post will focus on this second approach.

All source code for this post can be found in my demo GitHub repository. You may find it useful for easy reference. Additionally, this post assumes you understand how to use the Angular CLI.

If you followed the previous post, the next two sections will be identical. The differences between the two posts start at the “Saving the Tracking Code” section.

Setup

As the previous post, 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 for this post, I’m using the new format. (If you’d like to learn how to add the legacy code to your application, the steps are almost identical. You can reference the previous post for some pointers.)

Legacy Format:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
    
ga('create', 'UA-173474946-1', 'auto');
ga('send', 'pageview');

New Format:

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

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.)

The remainder of this post along with the demo in the repository will use the new format.

Saving the Tracking Code

As stated in the previous section, we’re going to use the new format of the tracking code for Google Analytics. Our code is going to need to accomplish two things:

  1. Load the external Google Tag Manager code
  2. Register a page view

You’ll first want to create a new service using the Azure CLI (e.g. ng g s google-analytics – this code tells the CLI to generate a new service called google-analytics).

In the newly created service file (google-analytics.service.ts should be located in your application’s src folder), paste the following code:

import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import { environment } from '../environments/environment';

declare var gtag: any;

@Injectable({
  providedIn: 'root'
})
export class GoogleAnalyticsService {

  constructor(private _router: Router) {
    this._router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((e: NavigationEnd) => {
      gtag('js', new Date());
      gtag('config', environment.googleAnalytics);
    });
  }

  init() {
    const script = document.createElement('script');
    script.src = 'https://www.googletagmanager.com/gtag/js?id=UA-173474946-1';
    script.async = true;
    document.getElementsByTagName('head')[0].appendChild(script);

    const gtagEl = document.createElement('script');
    const gtagBody = document.createTextNode(`
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
    `);
    gtagEl.appendChild(gtagBody);
    document.body.appendChild(gtagEl);
  }
}

NOTE: Make sure you update the code with your specific Google Analytics tracking id (highlighted on line 24).

The above code takes the new format of Google Analytics and accomplishes our two tasks listed above:

  1. Loads the external Google Tag Manager code and appends it to the body of the page (lines 23-34 – the init() function)
  2. When Angular has completed the navigation of the visitor (e.g. the NavigationEnd event), the page view is registered (lines 17-18). One thing to note here, we are NOT hard-coding our Google Analytics tracking id on line 18. Instead, we’re referencing an environment variable. More on this in the next section.

We’ve now added the service code. We’ll next need to tell the Angular dependency injector that the service is available for injection. But, before we proceed in doing so, we need to have a quick discussion on the environment variable environment.googleAnalytics on line 18.

Environment Variable

If you think about it, we don’t necessarily 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 allows us to create separate environment variable values for different environments.

If you navigate to your application’s src/environments/ folder, you’ll see two files (e.g. environment.prod.ts and environment.ts). You may have more depending on the current development status of your application, but these are the two initial configurations. The prod file is used for production, whereas the other file is used for all other environments. In these files, you can specify different values for environment variables depending on the environment/configuration you are targeting. The only rule of thumb is that, while the values may be different, the keys in both files must be identical.

Given that, in your environment.prod.ts file, add the key/value from line 3 of the following code block (replace the Google Analytics with your own id):

export const environment = {
  production: true,
  googleAnalytics: 'UA-173474946-1'
};

In your environment.ts file, simply add the key with an empty value:

export const environment = {
  production: false,
  googleAnalytics: ''
};

Now, when you build your application, depending on the configuration you specify, that configuration’s value for googleAnalytics will be inserted into your GoogleAnalyticsService. If you specify a development-type build (i.e. non-production), then an empty string will be provided and, therefore, you will not have to worry about Google Analytics tracking page views while your application is being developed and/or tested. On the other hand, if you specify the production build, your Google Analytics id will properly be inserted and page views will be successfully captured.

You can see and compare the two environment files here.

We are now ready to move forward and use our service.

GoogleAnalyticsService Provider

Again, we’ve created a service and added the necessary code for tracking page views, but before we can use it, we must inform Angular’s IoC container that the service is available.

In your application’s app/src/ folder, open the file app.module.ts and add the GoogleAnalyticsService as a provider. Your code should look similar to the following snippet (see the repository for the full example).

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { GoogleAnalyticsService } from './google-analytics.service';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [GoogleAnalyticsService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, the service (and the Google Analytics code) can be injected on each of your Angular application pages.

Initializing the Service

Before the page will begin tracking, the service must be initialized.  We’ll do this from our app.component.ts.  (See the repository for the file.)

import { Component, OnInit } from '@angular/core';
import { GoogleAnalyticsService } from './google-analytics.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'Google Analytics Service';

  constructor(private _$gaService: GoogleAnalyticsService) {  }

  ngOnInit() {
    this._$gaService.init();
  }
}

The code above initializes our service in three steps:

  1. Imports the service (line 2)
  2. Injects the service to our class (line 12)
  3. Calls the init() method on the Google Analytics service when our application is initialized (line 15)

Testing

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 id is stored in the environment.prod.ts file, which 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 environment 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.

Like What You See?

Subscribe to receive new posts in your inbox.

Privacy Preference Center