Sunday 9 April 2023

How To Use Google Analytics in Angular

 

The ultimate guide for implementing Google Analytics in challenging Single Page Applications — SPA (i.e. Angular)

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:

  1. 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.
  2. 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!

We have an experienced team at Ciphers Lab that can help you in setting a stunning store that will boost your sales online. get connected now 

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,

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.


We have an experienced team at Ciphers Lab that can help you in setting a stunning store that will boost your sales online. get connected now 

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!

Edit 1: (21st April 2017) From the user’s concerns, emails, and comments, I would like to update this article.

How to implement GTag.js for Local / Dev / Beta or Production Environments?

A problem in general terms: Using the above code implementation, It is considering development views and tracks the performance, which will not provide correct information from the data analysis point of view!

Solution: Let’s set it up dynamically for all environments.

Simply Read Data From External File On Your Prod Build

Ultimate 100% working approach: Here is the plan:

In this solution, you can put JSON files in your assets or somewhere else from where the JSON file can be accessible.

You need to add the GTagId value dynamically as a key-value pair in the JSON file and refer to your different environments. When the angular context is loaded in the browser, it will always refer tracking id from the JSON value. You only need to build it once, and only needs to update the value in the JSON file for various environments.

Add a globalconfig.json file and place it inside assets/config/globalconfig.json or somewhere else, where it is accessible publically:

{
"trackId":"YOUR_GOOGLE_ANALYTICS_TRACK_ID"
}

Now, when the angular application is initialized (someone browses the web application on their browser), it should read the above trackId value. To do this, add the following code in your app.component.ts (put it just after import statements)

import { APP_INITIALIZER } from '@angular/core';
import { AppConfig } from './app.config';
import { HttpModule } from '@angular/http';
//Add this function as initiating load method first
function initConfig(config: AppConfig){
return () => config.load()
}
@NgModule({
imports: [
...
HttpModule
],
...
providers: [
...
AppConfig,
{ provide: APP_INITIALIZER,multi: true, useFactory: initConfig, deps: [AppConfig]}
],
...
});
export class AppModule { ...}

also, update your providers:[] as shown above.

You need to add one another file app.config.ts as shown in the gist below, which will load the file and read the information for your entire application including all routes.

Here we added config as a global variable, which will share the value in the entire application, just like a standalone object.

public static config: Object = null; <-- Your global config variable

To read the value you can inject the dependency of your AppConfig file, and pass the variable to read in the argument of getConfig method. Update your app.component.ts file as below.

Note: Don’t forget to remove gtag.js script code from your index file, otherwise it will return duplicate tracking information.

Bingo Again 👏👏👏

We have an experienced team at Ciphers Lab that can help you in setting a stunning store that will boost your sales online. get connected now 

You are all set and ready to work in any environment with proper Google Analytics tracking added to your angular application.

Blog owner
https://medium.com/beingcoders/how-to-use-google-analytics-in-angular-9a6131979819

No comments:

Post a Comment