Stay updated

How to integrate Google Analytics into our Angular Web Apps
Google Analytics <3 Angular
Wednesday, September 30, 2020

As part of the development of an e-commerce platform, which a front-end has been developed with Angular 8, the customer asked us to track user activities, using Google Analytics, in order to have live statistics on products sold on the site.

Google Analytics is undoubtedly the best-known tracking product, and it offers several ways to track user visits on a website, time spent by users on each page and actions that he performs.

Tracking user activities is necessary for most companies in the world as it helps to provide valuable data to create effective marketing campaigns and improve the user experience.

Another feature is the monitoring of loading times and the accessibility of the site so that a developer could optimize his Web application.

Google Analytics was designed for multi-page applications, as it calculates the number of views by tracking the user’s navigation from one page to another.

Angular, on the other hand, is a framework for single-page applications (SPA), which means that the browser technically only loads one page and, whenever a page “changes”, the DOM is simply updating parts of it, by changing the components that form it.

So, even if the link in the address bar changes dynamically, we are always on the same page, and Google Analytics naturally cannot know – in its basic implementation – that we are on a different view.

Before starting the integration, we must register our application with Google Analytics and obtain a tracking ID. We go to the Google Analytics web page and log in with our Google credentials.

A drop-down menu will appear and we can click on the “Analytics” link.

Once logged in, we can fill the registration form with the details of the web application; then we must accept the terms and conditions and finally click the “Get Tracking ID” button.

We are led back to the dashboard where we can see our tracking ID, which we will use in our application.

In the administration section Tracking Info -> Tracking Code, we can obtain the javascript code to insert in our pages. It contains a link to an external file and the definition of the gtag () function, which is the main function for the integration of Google Analytics with others’ frameworks.

The code in the Global Site Tag section (gtag.js) must be inserted in the index.html file, as the last element of the head tag.

In this way, we can use the gtag () function in our entire Web application according to our needs.

As mentioned above, our Angular applications run within a page, and, in order to properly monitor pages through Google Analytics, we need to know the URL that the user navigates to without loading a new page.

To obtain the URL, we can subscribe to the router events and check if they are of type NavigationEnd and, if so, invoke gtag() passing the urlAfterRedirects property of the subscribed event as a parameter.

The call to gtag (), specifically gtag (‘config’, ‘[Tracking Id]’, { ‘page_path’: ‘[url]’}), records that the user has viewed the page at that URL.

To have a first (and certainly faster) integration of Google Analytics, which will allow us to track the user’s URLs, we can insert the instructions just typed in app.component.ts, since it is the main application file which is loaded at the highest level. Our app.component.ts file will look like this:

import{Router, NavigationEnd} from '@angular/router';
declare let gtag: Function;
export class AppComponent {
 constructor(public router: Router){ 
 this.router.events.subscribe(event => {
 if(event instanceof NavigationEnd){
 gtag('config', 'xx-xxxxx-xx',
 'page_path': event.urlAfterRedirects

There are other parameters we can use to further enrich the tracking stats. The list of all parameters is available on the official documentation page (https://developers.google.com/analytics/devguides/collection/gtagjs/pages).

Another fundamental feature of Google Analytics is the tracking of events, which adds an additional layer of data to the Analytics statistics.

To make the integration consistent and reduce the amount of duplicate code in our application, we can create an Angular service to use in our components.

Through the Angular CLI we can generate a service and add it to app.module.ts with the instruction:

ng generate s GoogleAnalytics

Our app.module.ts will be:

import {GoogleAnalyticsService} from './google-analytics.service';
 providers: [GoogleAnalyticsService],
export class AppModule { }

Inside GoogleAnalyticsService, we create an eventEmitter public function that will essentially run gtag() making sure the formatting is correct.

Of course, we must declare the gtag() function in order to expose the service to the outside.

Our GoogleAnalyticsService will look like:

declare let gtag:Function;
export class GoogleAnalyticsService {
 public eventEmitter( 
 eventName: string, 
 eventCategory: string, 
 eventAction: string, 
 eventLabel: string = null, 
 eventValue: number = null ){ 
 gtag('event', eventName, { 
 eventCategory: eventCategory, 
 eventLabel: eventLabel, 
 eventAction: eventAction, 
 eventValue: eventValue

We created the GoogleAnalyticsCartService service which is a wrapper for GoogleAnalyticsService:

export class GoogleAnalyticsCartService {
public addToChart(productId) {
 .eventEmitter(‘add_to_cart’, ‘shop’, ‘cart’, ‘click’, productId);
public removeFromChart(productId) {
 .eventEmitter(‘remove_from_cart’, ‘shop’, ‘cart’, ‘click’, productId);

To use this service, we need to import it into the component and run it when something happens (like a button click event) and pass the values ​​we want to monitor to the eventEmitter for execution.

In our implementation, we used the eventEmitter function to track the following events:

  • adding product to cart;
  • elimination of product from the cart.

We have created a component named ShopComponent that manages the addition of a product

In the case of addition of a product to the cart, we have a button that calls the SendAddToCartEvent function passing the product id as an argument.

<button (click)="SendAddToCartEvent(productId)">Add To Cart</button>

And, in our component, we handle SendAddToCartEvent to call the eventEmitter function defined earlier.

import{GoogleAnalyticsCartService} from './google-analytics-cart.service';
export class ShopComponent implements OnInit {
 public googleAnalyticsCart: GoogleAnalyticsCartService

In the same way, the events of elimination of a product from the cart will be managed through the eventEmitter function:


Another feature offered by Google Analytics is the user tracking.

In order to filter events and page views by user, the User-ID must be enabled in the Analytics configuration panel.

Once the User-ID is enabled, the current user can be configured in our Angular application, just by using:

gtag(‘set’, ‘userId’, userid)

where userid is a string that uniquely represents the system user.

At the time of user login, it is advisable to retrieve a parameter, such as an index or guid (not personal information such as name, email, address) and set it as userId.

As for event management, we have created a wrapper method to configure the user:

public setCurrentUser(userId: string){ 
 gtag('set', ‘userId’, userId);

that will be used in the component named LoginComponent:

import{GoogleAnalyticsService} from './google-analytics.service';
export class LoginComponent implements OnInit {
 public googleAnalytics: GoogleAnalyticsService
 login(username, password){
 var userId = this.http...

Google Analytics also allows us to check whether the operations on our Web application have been carried out within a user session or not.

Through the menu Audience -> Behavior -> User-ID Coverage, it is possible to obtain the data of the operations carried out by Assigned (logged in and tracked) and Unassigned (not logged in) users.

To view the operations filtered by the user, however, you need to create a view.

In the Tracking Info -> UserID menu, once the settings (User-ID policy and Session Unification) have been configured, we can create a view.

In this way, for each operation performed by users, it will be possible, via the Google Analytics panel, to filter the operations by user.

The example project attached to this article is a simple e-commerce Web application, with a list of static products that can be added to the cart, and another cart used to manage the products (increasing or decreasing the quantity).

We can run it by typing:

ng serve --watch

and browsing on http://localhost:4200, we get the dashboard:

by clicking on the name of the product, a detail page opens, whether by clicking on Add To Cart, the product is added to the cart.
By clicking on the cart icon at the top right, we can manage the quantities of products or remove them.

Once performed enough actions on our site, we can go to the Google Analytics panel to view the statistics of those actions.

To show the events, instead, we can go to Behavior-> Events, and from there filter by type of event, product id. and, of course, user id.

In this article, we showed you how to integrate Google Analytics into Angular projects to obtain stats and site events.

We wish we raised your interest in the topic.

The sample project with the code used in this article is available here.

See you at the next article!

Written by

Enrico Bencivenga