How To Properly Add Google Analytics Tracking to Your Angular Web App

There’s more to it than just copy-pasting the tracking code



Single-page application frameworks and libraries can be a blessing for developers but a pain when it comes to properly implementing tracking and analytics.

If you’ve ever worked with Google Analytics, you would have encountered the global site tag — or gtag.js. Google tells you to pass this code as the first item in the <head> area of the web page you want to track.

But when you’ve only got one page, as single-page applications built-in frameworks like Angular do, the copy and paste solution won’t work the way you need it to work.


How Angular Works

Angular is a single-page application framework, which means that your browser technically only ever loads one page. When a page ‘changes’, the DOM is merely updating a portion of the page as specified by the framework’s JavaScript code.

Components are the things that makeup parts of the visual jigsaw. While you may be navigating away from a particular view and the link in the address bar dynamically changes to match, you are still on the same root page.

This is because the browser doesn’t refresh your page and there’s no new page loaded. It’s still the same page — just a different view and the basic implementation of Google’s Analytics tag doesn’t know this.


It Starts With the Copy-Paste gtag.js Code

There are two versions of tracking through Google Analytics — ga and gtag. ga is the older and depreciated version, with Google pushing for gtag.js implementation instead.

To start, you’ll need to go into your Google Analytics panel and find the copy-paste code. You’ll need to copy this code, put it in the <head> section as suggested, minus the gtag('config', 'xx-xxxxx-xxx'); part in the snippet.

This little code snippet simply makes the gtag.js library available for your application’s consumption. gtag('config', 'xx-xxxxx-xxx'); function executes the page view portion of your webpage.

The gtag() function is what we’ll be dealing with for anything Google Analytics related.

Example of what the screen looks like inside Google Analytics.

Router Events Is the Secret to Your Angular Sauce

Angular has several event handling methods which can be used to access certain information. For Google Analytics, what we’re interested in is the URL a user has navigated to.

To extract this information, we can use navigationEnd method to access a property called urlAfterRedirects. This property contains the / portion of your routing URL.

So, for a URL that looks something like this http://localhost:4200/shop, it will give /shop as the value.

To use navigationEnd, you’ll need to import it and subscribe the event to call gtag() when something happens. You’ll also need to give your Angular component access to gtag by declaring it as a Function.

For code efficiency purposes, you can place all this in the app.component.ts file as it is the first file that gets called and loads at the top level of everything that eventually follows.

In short, your code should look something like this:

 ...
import{Router, NavigationEnd} from '@angular/router';
...
declare let gtag: Function;
...
export class AppComponent {
  constructor(public router: Router){   
      this.router.events.subscribe(event => {
         if(event instanceof NavigationEnd){
             gtag('config', 'xx-xxxxx-xx', 
                   {
                     'page_path': event.urlAfterRedirects
                   }
                  );
          }
       }
    )}
} 

There are other parameters you can use to further enrich your tracking. For the latest list of parameters, you can check them out on the Google Analytics tracking page views documentation page.


Event Tracking

Event tracking adds another layer of data to your Analytics statistics. Its implementation, however, is less laid back than page views and will require a little intervention to get the right data to Google’s free platform.

To keep everything cohesive and to reduce the amount of duplicate code across our application, we’re going to create an Angular service and use it in our components.

To do this, you can use the CLI to generate a service for you and then add it to your app.module.ts file as one of the providers.

To generate a new service using the CLI:

ng generate s GoogleAnalytics

What your app.module.ts code should look like:

 ...
import {GoogleAnalyticsService} from './google-analytics.service';
...
@NgModule({
...
   providers: [GoogleAnalyticsService],
});
... 

Inside your newly created service file, you’re going to create a public eventEmitter function which will essentially run gtag when it’s called and ensure that your formatting is correct and in the way that’s required by gtag.

You’ll also need to declare gtag as a Function to expose your service to the externally loaded library.

Your service code should end up looking something like this:

 ...
declare let gtag:Function;
...
export class GoogleAnalyticsService {
...
   public eventEmitter( 
       eventName: string, 
       eventCategory: string, 
       eventAction: string, 
       eventLabel: string = null,  
       eventValue: number = null ){ 
            gtag('event', eventName, { 
                    eventCategory: eventCategory, 
                    eventLabel: eventLabel, 
                    eventAction: eventAction, 
                    eventValue: eventValue
                  })
       }
} 

To use this service, you’ll need to import it into your component and run it when something happens — something like a button click event — and then pass the values you want to track to the eventEmitter to run.

So, in your HTML, you might have something like this:

<button (click)="SendAddToCartEvent()">Add To Cart</button>

Then, in your component where you’ll handle the SendAddToCartEvent(), you can call eventEmitter. Do note that you’ll need to import the service you created into your component for it to work.

Your component code should look something like this:

 ...
import{GoogleAnalyticsService} from './google-analytics.service';
...
export class ShopComponent implements OnInit {
...  
   SendAddToCartEvent(){ 
    this
     .googleAnalyticsService
     .eventEmitter("add_to_cart", "shop", "cart", "click", 10);
   } 
...
} 

You can create your own events and event categories. However, Google has a list of predefined ones ready for you to use. You can find the full list here.


Final Words

I’ve created an associated GitHub repository for your reference. It contains barebones Angular code so you can see how it all fits together in a working project. Feel free to use the repo however you want.

Implementing Analytics tracking is not hard once you understand how gtag.js and Angular routing works. Implementing it on a single-page and progressive web application can be a bit of a mystery for some but hopefully, that mystery is now less daunting.

Thank you for reading.

Comments

0 comments

About Author /

I code. I write. I hustle. Living the #devLife remotely. Subscribe to my newsletter to stay connected with my latest posts and dev thoughts.

Leave a Comment

Your email address will not be published.

Start typing and press Enter to search