Using Google Analytics with your SPA Angular 2 Web App

Using Google Analytics with your SPA Angular 2 Web App

In order to track navigation in your Single Page Application, it takes a little more work up front. This article explains how to use Google Analytics with an Angular 2 Web App.

First you’ll need to register your web domain with Google. There a few different ways to verify your site. Once verified you’ll be able to download a JavaScript snippet to add to your site. With a traditional (non-SPA) site, you just drop this into your layout template and you’d be good to go.

The technical details of how tracking SPA navigation is detailed in this guide with Google. The key to grab the creating key from the snippet. We’ll use that later in the implementation.

ga('create', 'UA-69737250-1', 'auto');

First add this to your index.html. This will be the only modification to that page.

<script async src='https://www.google-analytics.com/analytics.js'></script>

Next modify your package.json include the autotrack library from Google. 1.0.3 is the version available when this post was written.

"autotrack": "~1.0.3",

Next we’re going to create a service. This will be a global service instantiated when our app first loads.

import {Injectable} from '@angular/core';
require('autotrack');

@Injectable()
export class AnalyticsService {
    constructor() {
        (window).ga=(window).ga||function(){((window).ga.q=(window).ga.q||[]).push(arguments)};(window).ga.l=+new Date;

        (window).ga('create', 'UA-69737250-1', 'auto');
        (window).ga('require', 'cleanUrlTracker');
        (window).ga('require', 'eventTracker');
        (window).ga('require', 'outboundLinkTracker');
        (window).ga('require', 'urlChangeTracker');
    }

    pageView(url: string) {
        (window).ga('set', 'page', url);
        (window).ga('send', 'pageview');
    }

    //to track clicks on html attributes
    //ga-on="click"
}

If you have a app.module.ts, or a similar file, where you’re bootstrapping your application, add your service there to the providers: [] array.

From your component where you want to track the navigation, import the reference and inject it into your component class. Then on the ngOnInit log the page navigation. (This is not a full component code sample. Just the pieces you need for it to work).

import {AnalyticsService} from './../services/analytics.service'; //path will likely differ

  constructor(private _analytics: AnalyticsService) {
  }

  ngOnInit() {
    this._analytics.pageView('/login.html');
  }

That’s all there is to it. If you want to see if it’s working you can view all network traffic from the Chrome Developer Console, or of course log into your Analytics account to see if the traffic is being captured.

  • C Y

    I am getting the following error.

    src/app/services/analytics.service.ts (7,14): Property ‘ga’ does not exist on type ‘Window’.

    What am I missing?

    • JK

      Make sure you have this reference and also the autotrack npm package referenced in your package.json

    • Oleh Leskiv

      Try this

      import { Injectable } from ‘@angular/core’;
      import ‘autotrack/autotrack.js’;

      @Injectable()
      export class AnalyticsService {
      constructor() {
      ( window).ga = ( window).ga || ((…args) => {
      (( window).ga.q = ( window).ga.q || []).push(args);
      });
      ( window).ga.l = +new Date();

      ( window).ga(‘create’, ‘UA-100860879-1’, ‘auto’);
      ( window).ga(‘require’, ‘cleanUrlTracker’);
      ( window).ga(‘require’, ‘eventTracker’);
      ( window).ga(‘require’, ‘outboundLinkTracker’);
      ( window).ga(‘require’, ‘urlChangeTracker’);
      }

      pageView(url: string) {
      ( window).ga(‘set’, ‘page’, url);
      ( window).ga(‘send’, ‘pageview’);
      }

      // to track clicks on html attributes
      // ga-on=”click”
      }

Comments are closed.