When someone asks about Tracking web pages for analysis, generally Google Analytics product by Google comes up first in your mind, Right?
Because Google Analytics is a popular, trending, and powerful analytical tool as it is providing multipurpose utilities to track the usage of your web pages, desktop, and mobile performance, it can also analyze targetted audience and their taste findings from your website or application. Tracking real-time audience, the source of referrals to your website, Keywords for SEO for your websites, etc., features are widely used from Google Analytics as per my research.
How to implement Google Analytics for your Static or Dynamic Web Page Application?
(Just For Information — If you are not aware of how it works in legacy web pages or multi-page applications)
Generally, Google Analytics provides a small code snippet to track information that you need to put on each page of your static website. In case you are using a WordPress website, Blogspot, or other dynamic frameworks, you can put it to your footer, as the footer section is shared among the entire application. The tracking code will be executed on the initialization of your page, which means — when someone opens your web page, the tracking code start their internal work.
Google Analytics will ask you to put a Global Site Tag (gtag.js)
snippet to your <head>
tag for each file which you want to track the performance and for your search engine optimization.
How to implement Google Analytics for Angular Application?
Single-page application frameworks (like Angular 2+ versions) can help you create an app quickly, but if you’re not careful about your implementation, you could end up with a lot of code that doesn’t really add value to your product. Analytics tools like Google Analytics provide a great solution for adding tracking and analytics to your site, while also making it easy to implement.
The Issue:
- Angular is a single-page application
- Component-driven solution
- Never refresh the page (Like CTRL + F5 or Hard Reload)
- On navigation to other pages, it will never load a new page.
In the Angular project, only index.html
file contains <head>
a tag; If you put a gtag.js
code snippet, it will not track your internal components or their usage, performance, or audience navigation flow in your Google Analytics dashboard.
Angular is changing components using a routing strategy, one after another component — by following Component LifeCycle, which means your DOM is merely updating a component or small part of the page, But if you observe the address bar, it updates the URL on each time you navigate to another component(s). Still, the root page isn’t destroyed, you are standing on the root directory itself.
Solution for Angular + Google Analytics Implementation
Google Analytics is an advanced technology that every developer, SEO & marketing agent is blessed with! But Angular has its own limitations that are, on every route navigation doesn’t know how to capture components and hit the count++ for the new page.!
So, why don’t we trigger the event programmatically to tell google analytics, that a new page was visited by the user, and track and count that page performance individually?
Implementation Steps:
Follow below simple steps to get your work done before 10 minutes.
Prerequisites:
- I believe, your project is ready with a couple of routings and ready to integrate the google analytics code at least. If not ready — bookmark this article, and please make sure to be ready with at least a couple of routings.
- You must have a Google Analytics account with Property set up (You need a domain name to own your property) for your web application, so you can grab the Global Site Tag (gtag.js) code snippet to integrate with Angular.
You can find your gtag.js code snippet from Properties → Data Streams → Web stream details.
Moving ahead, In this example, I have a few routes like,
/login
/register
/dashboard
/dashboard/wallet
I will show you how you can use google analytics code to trigger the event to count each component individually.
<!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=<YOUR TRACKING ID>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date());gtag('config', '<YOUR TRACKING ID>'); </script>
If you are copy-pasting the above code, then replace <YOUR TRACKING ID>
with your tracking id, which can be found in the following path:
Google Analytics Dashboard → Properties → Data Streams → Web stream details
Open your index.html
file of the angular project, and put the above code with your tracking id before</head>
tag.
<html> <head> ... <base href="./"> <meta/> <style/> <link/><!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=<YOUR TRACKING ID>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date());gtag('config', '<YOUR TRACKING ID>', { send_page_view: false}); </script></head><body> <app-root>Loading...</app-root> ... <script/> <body> </html>
Important note: Now google will track the performance from your web pages, but we want to measure the performance from the internal components (our end goal), so I advise you to perform the below steps compulsory to avoid duplicate counts and false performance reports.
Confession: I faced the same issue already and I was so happy to see the doubled performance on my application views, audience and all are performing so well, but when I realized the truth, I updated the code as shown above!
When the user navigates to another component through the route, we need to intercept the request as follows:
Angular provides NavigationEnd
event, which can be subscribed from Router.events
so let’s take benefit of the prebuilt angular events. Alternatively, you can create your own interceptor to achieve the google analytics implementation purposes.
To extract such data, we will use urlAfterRedirects
event inside the NavigationEnd interceptor. This property contains the / fragment of your routing URL. For http://localhost:4200/dashboard
URL, urlAfterRedirects
will return /dashboard
.
Now open your app.component.ts
file, and add interceptor code as shown below in the gist. Check for code writer inside,
/** START : Code to Track Page View using gtag.js */
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
gtag('event', 'page_view', {
page_path: event.urlAfterRedirects
})
})
/** END : Code to Track Page View using gtag.js */
Put the above code snippet inside constructor and router events as depicted below,
import { CommonsServices } from './_services/commons.services';
import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError, Event, ActivatedRoute } from '@angular/router';
import { filter } from 'rxjs/operators';
import { Title } from '@angular/platform-browser';
declare const gtag: Function; // <------------Important: the declartion for gtag is required!
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
title: string = 'DigitalWorkerBees';
loadingDataImg: boolean = false;
constructor(private router: Router, private activatedRoute: ActivatedRoute,
private titleService: Title) {
router.events.subscribe(event => {
this.navigationInterceptor(event);
});
/** START : Code to Track Page View using gtag.js */
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
gtag('event', 'page_view', {
page_path: event.urlAfterRedirects
})
})
/** END : Code to Track Page View using gtag.js */
//Add dynamic title for selected pages - Start
router.events.subscribe(event => {
if(event instanceof NavigationEnd) {
var title = this.getTitle(router.routerState, router.routerState.root).join(' > ');
titleService.setTitle(title);
}
});
//Add dynamic title for selected pages - End
}
ngOnInit() {
window.scrollTo(0, 0);
}
// collect that title data properties from all child routes
// there might be a better way but this worked for me
getTitle(state, parent) {
var data = [];
if(parent && parent.snapshot.data && parent.snapshot.data.title) {
data.push(parent.snapshot.data.title);
}
if(state && parent) {
data.push(... this.getTitle(state, state.firstChild(parent)));
}
return data;
}
// Shows and hides the loading spinner during RouterEvent changes
navigationInterceptor(event: any): void {
//Triggered When the navigation starts
if (event instanceof NavigationStart) {
this.loadingDataImg = true;
}
//Triggered When the navigation ends
if (event instanceof NavigationEnd) {
this.loadingDataImg = false;
}
// Set loading state to false in both of the below events to hide the spinner in case a request fails
if (event instanceof NavigationCancel) {
this.loadingDataImg = false;
}
//Triggered When the error occurrs while navigation
if (event instanceof NavigationError) {
this.loadingDataImg = false;
}
}
}
Gist code snippet for Angular And Google Analytics code implementation
Bingo
Woo Hoo! You are done with the implementation before 10 minutes. Now deploy your application to your respective domain and check the Google Analytics dashboard.
It will show you the number of page views, device, and performance tracking for your hosted application. Let’s say I opened the web application from a desktop and mobile device with a gap of a few minutes, it will show data as shown below.
(In the modern decade, google updated its view, look and feel to display analytics as below)
Traditional Google Analytics was showing infographics as below.
How is your experience with this article? Please comment your thoughts below. It will be always appreciated!
© Originally published on How to Use Google Analytics in Angular Project by Author Rakshit Shah.
Also Republished on Medium - How To Use Google Analytics in Angular by Author Rakshit Shah.
How to implement GTag.js for Local or Production Environments?
Visit this answer, I have updated the answer after doing proper research!
http://www.9mood.com/how-to-use-google-analytics-in-angular/
This is really great article, I thought google analytics is about js code to be put under head tag. lovely answer