Angular & Google Analytics - The Complete Guide
Who else wants to use Google Analytics in their Angular application?
Using Google Analytics and Angular together is easy.
Yup buddy! 🤓
Adding Google Analytics to your Angular app is not hard at all.
There's no need to sweat like a pig.
Or blow a fuse.
In this complete guide I'm going to show you how to integrate Google Analytics into your Angular application.
Want to skip the read and add Google Analytics to your Angular application now? Then click here.
Table Of Contents
- What is Google Analytics
- Should you use Google Analytics with Angular?
- Disadvantages of using Google Analytics with Angular
- How do you use Google Analytics with Angular?
- First Step: Google Analytics Setup
- Here's how to add Google Analytics to your Angular application (the easy way)
- Here's how to add Google Analytics to your Angular application (the hard way)
What is Google Analytics?
Google Analytics is a powerful, free, analytics service offered by Google. Anyone can use it to track and report the traffic on their website.
As of 2019, Google Analytics has become the most popular web analytics service on the web. Google Analytics is not just limited to websites though. They also provide an SDK making it possible to grab usage data from mobile apps on the iOS and Android platforms.
It's important to know that Google Analytics can be blocked by privacy-oriented browsers, browser extensions, ad-blocks and other firewalls. In the recent years some companies have left Google Analytics for privacy-focused alternatives.
Should you use Google Analytics with Angular?
So what are some of the reasons you should be using Google Analytics?
And are there any advantages?
Google Analytics is without doubt the most powerful and popular analytics tool that can be used for free. You can monitor all kinds of metrics like page views, sessions, bounces, visits and user engagement. It allows you to easily see how users are interacting with your website or application and make wiser marketing and business choices.
It was originally created for static websites and wasn't designed for single page applications created with Angular (or other web libraries and frameworks). This makes it a bit trickier to add Google Analytics to an Angular application but it is doable and really not that hard.
If you want to discover how users are interacting with an Angular application then Google Analytics is definitely the cheapest, easiest and quickest way to get started.
Disadvantages of using Google Analytics with Angular
One of the biggest disadvantages of using Google Analytics is privacy.
In a 2019 blog article on FastCompany one of their writers recommended that we ditch Google Analytics.
Because of these types of concerns with Google Analytics alternatives like Plausible Analytics and Microanalytics have popped up.
So is there a time when you should not use Google Analytics with Angular?
That's a question you'll have to decide. But remember that most users that care about privacy have already installed firewalls and browser extensions to block Google Analytics.
How do you use Google Analytics with Angular?
When integrating Google Analytics into our Angular application we have two options.
- Use a 3rd party library built by the open-source community.
- Create our own Angular service that communicates with our Google Analytics account.
Which one should you choose?
Should you use a library or build your own connector?
Obviously, the first choice is the easiest and quickest way to use Google Analytics with Angular. But it might not offer the customization and tracking that we need. In that case we'll need to create our own service that communicates with the Google Analytics services.
First Step: Google Analytics Setup
The first step is to go to the Google Analytics home page and create your account.
If you already have an account then you can sign in instead.
Once you are signed in click on "Admin" in the bottom left corner of the page.
Then click Create -> Property.
Give your new property a name and properly configure the other options. Then click Next.
Answer the business information questions and then click Next.
Then select your business objectives.
Now we'll need to set up how we're going to collect data in Google Analytics.
Since we're adding Google Analytics to an Angular web application we'll select the web platform.
Now you'll need to specify the URL of your website as well as the name of the new data stream (the data coming in from your Angular application to Google Analytics).
This should take you to a page that displays the new web stream details. The MEASUREMENT ID
is important and we'll need it for the next step.
Yada! You're now ready to start using Google Analytics with Angular.
🥳 🥳 🥳
Here's how to add Google Analytics to your Angular application (the easy way)
The first step is to install the ngx-google-analytics package.
npm install --save ngx-google-analytics
Once installed, you'll need to import it into your app.module.ts
file like this.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxGoogleAnalyticsModule } from 'ngx-google-analytics';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
NavBarComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgxGoogleAnalyticsModule.forRoot('MEASUREMENT-ID')
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Run your Angular application and you should see a new user show up in the Google Analytics real-time report.
There's a problem though. 🤨
With the current configuration the Google Analytics package for Angular is not sending the various page views to the analytics service. This means that as a user navigates your Angular application you won't be able to see what pages they're navigating to.
To fix this all we have to do is import the NgxGoogleAnalyticsRouterModule
module. Like this.
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxGoogleAnalyticsModule, NgxGoogleAnalyticsRouterModule } from 'ngx-google-analytics';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavBarComponent } from './core/nav-bar/nav-bar.component';
@NgModule({
declarations: [
AppComponent,
NavBarComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
NgxGoogleAnalyticsModule.forRoot('MEASUREMENT-ID'),
NgxGoogleAnalyticsRouterModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
And that's how to add Google Analytics to your Angular app the easy way.
If you're interested in learning more about this package and all of it's options you can read the documentation here.
But what about the hard way?
How to add Google Analytics to your Angular app (the hard way)
The first step is to go into the settings for your Google Analytics property and find the Global site tag
.
You want to copy the global site tag into the head
of your index.html
file.
It should look sorta like this.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular Application</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT-ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'MEASUREMENT-ID');
</script>
</head>
<body>
<app-root></app-root>
</body>
</html>
This is a good start but again there is a problem. We're not quite finished because Google Analytics is not notified when we route to a page inside our SPA.
To fix that, we'll subscribe to the Angular router inside the app.component.ts
file and send the new routes to Google Analytics.
import { Component } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
declare const gtag: Function;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public router: Router) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
gtag('config', 'MEASUREMENT-ID', { 'page_path': event.urlAfterRedirects });
}
})
}
}
Woo! We've installed Google Analytics and are now sending page views to the Google Analytics servers.
Time for some analytics
So what do you think of using Google Analytics in your Angular app?
Is it worth it?
And was it hard to get it set up and working?
Let me know in the comments below.
For now, I've gotta run over to Google Analytics and analyze who's whizzing around on my blog.
Angular Developer