Integrating Google Analytics With Angular 2+

Integrating Google Analytics With Angular 2+

For this tutorial, knowledge of HTML, CSS and JavaScript as well as some familiarity with Angular 2 development is expected. An understanding of Google analytics would be beneficial but is not absolutely necessary as it will be explained in the article.

For this tutorial, knowledge of HTML, CSS and JavaScript as well as some familiarity with Angular 2 development is expected. An understanding of Google analytics would be beneficial but is not absolutely necessary as it will be explained in the article.

Table of Contents

Introduction

Google Analytics is at the forefront when it comes to offering effective ways to track the pages a user visits, the time he spends there and what he is doing. This makes it a necessity for the majority of companies around the world in providing valuable data for creating effective marketing campaigns, improving their user experience and so forth. Google Analytics goes even further to monitor the load times and accessibility of your site which gives you, as a developer, the ability to optimize your web application.

However, Google Analytics was designed with Multi- Page Applications in mind, because it calculates the number of page views by monitoring the navigation of users from one page to another. As Angular developers, we build Single Page Applications and this means our entire web app runs within one page which makes it hard for us to monitor user activity. Our application resources are dynamically loaded on the client side and this results in incorrect data being sent to our site tracker.

How do we fix this?

We need to emit an event every time we navigate through our application. We do this by using the Router.event to provide us with an observable that we can subscribe to and receive information we can send to our Google Analytics page. Well, let’s get started.

Register Your App on Google Analytics

First and foremost, we need to register our application with Google Analytics and get a Tracking ID. Go to the Google Analytics webpage and click sign in. This will show a drop down where we will click “Analytics”.

Click on the sign up button to go to the registration form where you will fill in the details about the web application. You then click the “Get Tracking ID” button and accept the terms and conditions. This will take you to your dashboard where you will see your new Tracking ID which you will use later.

Setup your Angular Application

We will be using the Angular CLI for this example. If you do not have the Angular CLI installed on your computer, run the following command.

 npm install -g @angular/cli

Now create your new project.

ng new angularGoogleAnalytics

Our application is still empty and as a result we cannot yet track a user activity. We need to generate two new components i.e. component-1 and component-2 that we will navigate between.

ng g component component-1
ng g component component-2

Now that we have our two components, we need to set up our router such that we can navigate between them. This is what we will track with Google Analytics. In our app.module.ts, import the RouterModule and set up our routes.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router'; //Import the Angular router module and Routes

import { AppComponent } from './app.component';
import { Component1Component } from './component-1/component-1.component';
import { Component2Component } from './component-2/component-2.component';

export const appRoutes: Routes = [
  {path: '', component: Component1Component},
  {path: 'component-2', component: Component2Component}
];

@NgModule({
  declarations: [
    AppComponent,
    Component1Component,
    Component2Component
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Once this is done, add a router outlet to our app.component.html file to output our different components.

<router-outlet></router-outlet>

Add the Google Analytics Tracking Code

You now have an Angular app with two components that you can navigate easily between. It is now time to add our Google Analytics code to track the user activity. We do this by adding the tracking code into our index.html file. However, since we are building a single page application, we must send our page views manually and therefore, we remove the ga('send', 'pageview');line, which is responsible for transmitting the page views, from our code.

<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-xxx', 'auto');  // Change the UA-ID to the one you got from Google Analytics

  </script>

To manually send our page views to Google Analytics, we import the Router and NavigationEnd from @angular/router into our app.component.ts. We then subscribe to the router.events property to trigger a page view when we move from one route to another.

import { Component } from '@angular/core';
import {Router, NavigationEnd} from '@angular/router'; // import Router and NavigationEnd

  // declare ga as a function to set and sent the events
 declare let ga: Function;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  title = 'app';

   constructor(public router: Router) {

    // subscribe to router events and send page views to Google Analytics
    this.router.events.subscribe(event => {

      if (event instanceof NavigationEnd) {
        ga('set', 'page', event.urlAfterRedirects);
        ga('send', 'pageview');

      }

    });
  }

}

Now we need to create links to navigate between our components. Add the following router link to your component-1.component.html file to navigate to component-2.

<p>
  component-1 works!
</p>

<button type="button" class="btn btn-primary" routerLink="/component-2">Go To Component 2</button>

Add another router link to component-2.component.html to navigate back to component-1.

<button type="button" class="btn btn-primary" routerLink="/">Go To Component 1</button>

Now serve your application, go to http://localhost:4200 and move fromcomponent-1 to component-2.

Congratulations, you can now track the different pages a user visits when he accesses your website.

Add Event Tracking

We may want to do more than just track a users page visits on a site. Using a real world example of a picture sharing app, we may want to track when a user clicks the like button on a particular photo and why. We do this by creating a service with an event emitter that takes in the eventCategory, eventAction, eventLabel as well as eventValue and submits it to Google Analytics.

import { Injectable } from '@angular/core';

declare let ga:Function; // Declare ga as a function

@Injectable()
export class GoogleAnalyticsService {

  constructor() { }

  //create our event emitter to send our data to Google Analytics
   public eventEmitter(eventCategory: string,
                   eventAction: string,
                   eventLabel: string = null,
                   eventValue: number = null) {
    ga('send', 'event', {
      eventCategory: eventCategory,
      eventLabel: eventLabel,
      eventAction: eventAction,
      eventValue: eventValue
    });

                   }

}

We then import our service to the app.module.ts file and add it as a provider.

import {GoogleAnalyticsService} from "./google-analytics.service"; // import our Google Analytics service

providers: [GoogleAnalyticsService], //add it as a provider

Assuming that our component-2 is a page where a user has shared a picture, we add an image and a like button to the component-2.component.html. Our like button, will have a click event that triggers the sendLikeEvent() function.

<div class = "row" style="padding-top:150px;">
  <div class = "col-md-5 offset-3 text-center">

    <img src="assets/man-1352025_960_720.png" width="500px" height="300px" style="padding-bottom:30px;"><br/>
    <button type="button" class="btn btn-primary btn-lg center" (click)="SendLikeEvent()">Like</button>

  </div>
</div>

In the component-2.component.ts file, we import our GoogleAnalyticsService and add it to our sendLikeEvent() function. This will pass our eventCategory, eventAction, eventLabel and eventValue details to our service which will submit them to Google Analytics.

import { Component, OnInit } from '@angular/core';
import {GoogleAnalyticsService} from "../google-analytics.service"; // import our analytics service

@Component({
  selector: 'app-component-2',
  templateUrl: './component-2.component.html',
  styleUrls: ['./component-2.component.css']
})
export class Component2Component implements OnInit {

  constructor(public googleAnalyticsService: GoogleAnalyticsService) { }

  ngOnInit() {
  }

  SendLikeEvent() {
    //We call the event emmiter function from our service and pass in the details
    this.googleAnalyticsService.eventEmitter("userPage", "like", "userLabel", 1);
  }

}

Now go to your browser and click the like button on your component-2 page.

Check your Google Analytics Dashboard’s real time event tracker and you will see the values we passed in from our component-2.

Congratulations, you are now also able to track user events on your web application.

Conclusion

Google Analytics is a great tool for tracking user activity and we have seen how it integrates into an Angular application to track page views and events. We have also seen a small example of how events tracking could be used and I hope that this has given you a few ideas on how you could integrate it into your own projects and use that data to optimize, market and evolve.

I hope you have enjoyed this article and remember to always keep learning.

Related Posts

Full Stack Web Development with Angular and Spring MVC

Angular 7 Tutorial - Learn Angular 7 by Example

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Building Web App using ASP.NET Web API Angular 7 and SQL Server

Build a Basic Website with ASP.NET MVC and Angular

Angular 7 (formerly Angular 2) - The Complete Guide

Learn and Understand AngularJS

The Complete Angular Course: Beginner to Advanced

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

Important reasons for developers to adopt Angular JS development

 Important reasons for developers to adopt Angular JS development

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular...

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular has been a top choice for web development and it's the latest version AngularJS has gained popularity in the industry. This java script framework has created its prominent position in creating web apps.
Regardless of whether there are numerous different systems accessible for web development, AngularJS can support among them all. Since its introduction in the market, Angular has been creating waves in the market.

Introduction

Angular js is a powerful framework that was developed by Google. It is used to build dynamic apps with power-packed features. It was first introduced in 2010 and created by developers at Google. This framework was created to simplify and remove the challenges in creating dynamic apps. It uses HTML, CSS, and java script to create dynamic single-page applications. Angular Js is inclusive of Mongo DB and it is a frontend fragment of Mean Stack. In the developer's community, Angular is considered as a reliable and fast Java script framework. Many popular apps like PayPal. You tube, Netflix, the guardian, Lego are built using the AngularJS framework.

In this blog, we are listing some compelling reasons to pick angular development to familiarize you with its potential

• Open-source framework: It is not a library but open-source frameworks that enable the developers to build well-performing single page web applications. Just after its launch, it became hugely popular among the developers and it is not going to come at a halt.

• Simplified MVC structure: Developers use AngularJS to build robust and interactive web applications. AngularJS framework uses MVC architecture to create interactive applications. AngularJS makes it easy for developers to create apps as they are only required to split the applications.

• Extensive community: As angular is built by Google, it is backed by a very large community of professionals. The Angular JS conferences of the professionals are held all over the world. Hackathons are also organized in IT communities that include some professional and skilled engineers who can help with the queries and questions related to Angular.

• Declarative code system: In Angular JS developers can create declarative patterns by using declarative paradigms. It enables developers to be less heavy, and easy to read. In this framework, the developers get data models that are not too complex to write that abolishes the need to use any getter/setters and with easy data manipulation.

• Two-way data binding: It is one of the impeccable features that makes Angularjs popular in the developers' community. It allows seamless projections of the models and data binding. In this framework, any changes in the user interface make an impact on the application objects. The developers are not required to fresh the cycle and that makes it vulnerable to bugs.

• Using directives: AngularJS makes use of Directives as the developers can build custom HTML tags that function as custom widgets and it can be possible using directives. Its implications are also in the case of the use of decorating components and manipulation of DOM elements in appealing ways.

• Enterprise-level testing: When using Angular JS there is no need for demanding any other supplementary framework or additional plugins. In the process, parts of applications are put in the angular framework which is not too complex for manipulation. In module separation, developers can load essential services in an effective way for the performance of automatic testing.

• Client-side situation: AngularJS mainly works at the client-side and it is fully compatible with both web and mobile browsers. It can function with any projects without the need for any backend notifications. The developers can easily use AngularJS for the front end of applications.

• Easy to use: AngularJS is rich with its features and facilitates developers to reduce any need for writing codes. It reduces the burden of developers by the application of MVC architecture and data models.

Many other significant features make AngularJS prioritize by the developers than other Javascript frameworks. The above-mentioned reasons have made it the top choice for reputed companies all across the globe for web development. Developers at the company master the skills to work with Angular JS development for web. The company is equipped with dedicated professionals having sound technical knowledge of working with AngularJS. We offer offshore services to extend our reach all across the globe with various models. We have more than 15 years of experience in the industry that we use to deliver high-quality solutions by leveraging the latest technology and quality standards.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]