Implementing Google Analytics on your website is quite an easy exercise and takes only a minute. You can simply copy-paste the tracking code (available here) on the website and you’re done installing this powerful tool in no time. After Implementing Google Analytics, what you get is – instant access to the number of visitors, their demographics, on-site visitor behavior, what content they viewed, how long did they stay on your website and other infinite insights. Implementing Google Analytics on a SPA can be tricky and overwhelming
However, Implementing Google Analytics on a SPA (Single Page Application) framework built on Angular 2 app can be tricky and overwhelming. Recently, in one of my projects, when I was asked to implement page views and other events, I had to roll up my sleeve and dig into it myself. Though the implementation was successful, I thought to share my experience/learning in this blog.
The Challenge
In general, when a user navigates to the other pages of a website, Google Analytics code triggers a pageview event using a simple code which is provided by Google. (You can get your code here.) This code enables you to calculate the number of views on a particular page of the website. This snippet code runs every single time when the user interacts with a page or loads a new page.
However, in the case of a Single Page Applications (SPAs), the website loads all its resources including pages/views on the first page itself. When a user navigates within the website or interacts with a particular page, the content of that page loads dynamically, without a need to refresh the page/load the page again. Because a full page request is never made, the pageviews event does not get triggered and hence Google Analytics does not capture session duration, resulting in showing an inaccurate visitor data. Hence, in any SPA, it is imperative to track the virtual page views manually.
The Solution - Implementation of Pageviews and Tracking Events
Though there are several libraries available to implement analytics and get insights such as Angulartics2; but I chose one of the simplest solutions of all.
Here is the step-by-step process to implement pageview and tracking events in a single page application.
Step 1: Since I wanted TypeScripts typing-features, I had to install the required typings from npm. Once installed, you can run the below command in your terminal:
npm install –save-dev @types/google.analytics
Step 2: It’s now time to add Google Analytics code. Since we are in a Single Page Application, it is important to note that we must send the pageview manually.
To do this, it is imperative to add the tracking code to the index.html (src/index.html) file. Please ensure that once the tracking code is added, it is critical to remove the last line as it is responsible for transmitting the pageview.
<!-- 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'); // paste the code till here, have to remove below line.
// ga('send', 'pageview'); // remove/comment this line, as we’re handling this manually.
</script>
<!-- End Google Analytics -->
Step 3: To be able to capture the pageview manually, it is advised to monitor and capture the router events in the AppComponent and instantly forwarding them to Google Analytics.
Here is the app.component code:
import {Component} from "@angular/core";
import {Router, NavigationEnd} from "@angular/router";
declare var ga: Function;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor(public router: Router) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
}
}
That’s it! By following the first three steps, you are now able to send the pageviews to Google Analytics.
Step 4: It is always better to understand your user behavior especially in a real-time application. To get these insights, we need to submit some of the events to Google Analytics.
Here is the code that enables you to understand the user behavior accurately. The below mentioned lines of code can be placed on a button. When a user clicks on this button, an event is created and sent to Google Analytics. To make this function reusable, it is advisable to store this simple code in a service.
import {Injectable} from "@angular/core";
declare var ga: Function;
@Injectable()
export class GoogleAnalyticsEventsService {
public emitEvent(eventCategory: string,
eventAction: string,
eventLabel: string = null,
eventValue: number = null) {
ga('send', 'event', {
eventCategory: eventCategory,
eventLabel: eventLabel,
eventAction: eventAction,
eventValue: eventValue
});
}
}
It’s now time to call the service through module:
import {GoogleAnalyticsEventsService} from "./google-analytics-events.service";
providers: [
GoogleAnalyticsEventsService
],
Now, create a button in app.component.html
<button>Submit an Event</button>
Finally, create ‘submitGAEvent’ function in app.component.ts
import {Component} from "@angular/core";
import {Router, NavigationEnd} from "@angular/router";
import {GoogleAnalyticsEventsService} from "./google-analytics-events.service"; //call the service
declare var ga: Function;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor(public router: Router, public googleAnalyticsEventsService: GoogleAnalyticsEventsService) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
}
submitGAEvent() {
this.googleAnalyticsEventsService.emitEvent("testCategory", "testAction", "testLabel", 10);
}
}
That’s it. You will now see that you have implemented the pageview and event tracking in your Angular2 App.