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 -->
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  ga('create', 'UA-XXXXX-Y', 'auto');
<!-- 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;

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

  constructor(private router: Router){ event => {

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