Enable Google Analytics in Angular2+ Projects

Google Analytics is the go to library for user interaction analyses with the web and mobile apps. It’s a free and very mature library, and you can integrate it with other Google products like Adwords. I wanted to integrate analytics library with an Ionic 3 based app that I have. So, I tried few plugins available in npm repository, but they had one or more issues and were not a good fit for my requirements. Therefore, I decided to create one that will help me in learning basics of Angular library and how it works.

So, I created ng2-google-analytics library to resolve issues that I was facing. Few of feature of library are:

  1. It works with applications that do not change url on page navigation.
  2. Plugin is compatible with multiple version of Angular versions. (Preferably, All Angular2+ versions)
  3. It is capable to register multiple tracker IDs. You can find more about this on the official analytics docs.
  4. The library should only trigger critical events and pages views as I only wanted to know how many users registered to my site and 3 to 4 more events. Auto trigger captures all page views and it is not what I required.

Sadly, I was not able to build single version of my library to support Angular 2-10 due to syntax change of `@Injectable()` in Angular 6+ Service. So, I created two versions of library.

Version 1.x.x: https://www.npmjs.com/package/ng2-google-analytics supports Angular 6+ projects, and

Version 0.x.x: https://www.npmjs.com/package/ng2-google-analytics supports Angular 2-5 projects.

How to install ng2-google-analytics library in your project?

1. Install ng2-google-analytics npm package.

// if your project is Angular6+, or
npm i ng2-google-analytics 
// if your project is based on Angular version 2-5
npm i ng2-google-analytics@0.2.0 

2. Then, import Ng2GoogleAnalyticsModule in `app.module.ts` file.

3. After that, call initialize function from app.component.ts.

// add Ng2GoogleAnalyticsService in app.component.ts
import {Ng2GoogleAnalyticsService} from 'ng2-google-analytics';
 
// add in constructor
constructor(
    public ga: Ng2GoogleAnalyticsService
    ...
  ) {
    //initialize service with your Google Aanlytics Token
    ga.initialize('UA-XXXXXXX-1');
  }

After initialisation, you angular project is ready for Google Analytics. You can now use this library’s setPage and trackEventV2 functions to set page views and track events respectively.

4. Track Pages using setPage function. This function takes two arguments

pageName: This is usually the name of current page.

trackerName: Optional, this property is only needed when you are using two different trackerId’s in one project.

Example code:

//add Ng2GoogleAnalyticsService in constructor
constructor(
    public ga: Ng2GoogleAnalyticsService
   ) {
  }

//track page view
ngOnInit(){
   this.ga.setPage('register.html');
   //or
   this.ga.setPage('register.html', 'myTrackerName');
 }

4. Track events using trackEventV2 function. This function also takes two arguments

eventObj: This object has four properties eventCategory, eventAction, eventLabel, eventValue. Out of these eventCategory and eventAction are required property.

trackerName: Optional, as explained above.

Example code:

// or call trackEvent2 which takes first param as object
    this.ga.trackEventV2({
      eventCategory: 'Register', 
      eventAction: 'Submit', 
    });
    
    // or call like this 
    this.ga.trackEventV2({
      eventCategory: 'Register', 
      eventAction: 'Submit', 
      eventLabel: 'Register Button',
      eventValue: 1
    });

5. Add additional trackers using `setAdditionalTraker` function

This step is optional and is only required when you need to add more than one google trackers in project. This function takes two argument: trackerId and trackerName. Example code to use additional trackers:

//call this function to set additional tracker
  this.ga.setAdditionalTraker('UA-XXXXXX-2', 'myCustomTrackerName')
 
  // you can now send page views to your new trackingId
  this.ga.setPage('register.html', 'myCustomTrackingName');
 
  //or send events to new tacking id
  this.ga.trackEventV2({
    eventCategory: 'Register', 
    eventAction: 'Submit', 
    eventLabel: 'Register Button'
  }, 'myCustomTrackingName');

6. Enable Google Tracking for all pages.

This plugin also supports automatic tracking of pages. Though It was not my initial requirement, it gives you enough flexibility to use this plugin.

// add in constructor
constructor(
    public ga: Ng2GoogleAnalyticsService
    ...
  ) {
    //initialize service with your Google Aanlytics Token
    ga.initialize('UA-XXXXXXX-1');
 
    // or if you want all pages tracked automatically
    ga.setAutoMode();
  }

I encourage you all to have a look at the source code from github repo. You can also report any bugs or enhancements from GitHub repository. Happy Coding.

Leave a Reply

%d bloggers like this: