Month: January 2017

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=''></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';

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

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() {

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.