Track Angular page views in Google Analytics

Tracking Angular page views with Google Analytics can be done using the Google analytics universal tracking code that should be placed before any other script or style tags within the tag making sure you replace UA-XXXXX-Y with your own tracking code. Because we’re tracking page views inside of angular we have to remove the line ga(‘send’, ‘pageview’); so we do not track the initial page view twice.

<!-- Google Analytics -->
<script>
  (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-XXXXX-Y', 'auto');
</script>
<!-- End Google Analytics -->

Subscribing to Angular router events within our AppComponent we check for view/page changes using the NavigationEnd event, sending the new Url to google analytics. Finally using the environment.production flag we can make sure we only track page views in production mode, otherwise log it to console.

// app.component.ts
import { Component } from '@angular/core';
import { NavigationEnd, Router } from "@angular/router";
import { environment } from "../environments/environment";

// allow use of global window variable
declare var window: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(private router: Router){

    this.router.events.subscribe( event => {

      if (event instanceof NavigationEnd) {
        if(environment.production) {
          // if production mode send
          window.ga('set', 'page', event.urlAfterRedirects);
          window.ga('send', 'pageview');
        }else{
          console.log('pageview', event.urlAfterRedirects);
        }
      }
    });
  }
}