Event Tracking With Google Analytics in Angular

Event tracking with Google Analytics is a great way to track user behavior in your application and it doesn’t require much effort to implement. Assuming your application was scaffolded using the Angular ng-cli tool, you can add an attribute directive to your application that will send click events to your Google Analytics in just a few minutes.

Adding Google Analytics

To implement event tracking in your Angular application, you first need to add Google Analytics to it. You may use the following Google Analytics debug script. That script outputs all Google related calls to the console. For a production use case, you may want to use the production Google Analytics script that does not do that.

  <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_debug.js','ga');

      window.ga_debug = {trace: true};
      ga('create', 'xxxx-xxxx-xx', 'none');
      ga('send', 'pageview');


  </script>

Create Directive

Next step is to create an attribute directive. Using the ng-cli tool, run the following :

ng generate directive button  

This will create a directive as well as update the app.module.ts file. Inside that directive, add the following code snippet.

import { Directive,HostListener,Input } from '@angular/core';


@Directive({
  selector: '[eventTracker]'
})
export class ButtonDirective {

  @Input('eventTracker') option:any;

  @HostListener('click', ['$event']) onClick($event){

    (<any>window).ga('send', 'event', this.option.category, this.option.action, {
      hitCallback: function() {

        console.log('Tracking is successful');

      }

    });

  }
  constructor() { }

}

That code snippet creates an attribute directive that can be added to any element that you want to track clicks on. Here is an example on how to use it.

<!--The content below is only a placeholder and can be replaced.-->  
<div style="text-align:center">  
  <h1>

    <button [eventTracker]='{"category":"user","action":"click"}'>
      Click Me

    </button>



    Welcome to {{title}}!
  </h1>

</div>  
<h2>Here are some links to help you start: </h2>  
<ul>  
  <li>
    <h2><a target="_blank" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
  </li>
  <li>
    <h2><a target="_blank" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
  </li>
  <li>
    <h2><a target="_blank" href="https://blog.angular.io//">Angular blog</a></h2>
  </li>
</ul>  

Checking Google Analytics

Once you created the event tracking directive, attach it to an element, launch the application and click on the element. Your Google Analytics should have caught the event.