DEV Community

Ankit Prajapati
Ankit Prajapati

Posted on • Originally published at ngdevelop.tech

Angular SEO - Integrate Google Analytics in Angular

Google Analytics is a popular analytical tool for web and mobile applications from Google. It helps to track real-time and historical website traffic stats.

Google Analytics Real-Time Traffic Stats

Google Analytics data helps to do SEO (Search Engine Optimization) of web and mobile apps.

Key Features of Google Analytics

  • Tracking web site traffic, page views, sessions, bounce rate.
  • Tracking traffic sources, events, conversations, referrals.
  • Provides information about new users and returning users details, page load time.
  • Provides information about user demographics, device type, mobile device screen resolution, language, browser and OS details, network details
  • User acquisition details, Search console details like search queries, landing pages.
  • Campaign details, Traffic through Google Ads, social media traffic.

and many more things. It provides reports of each above feature, which helps to analyze your users and take further business decisions to increase the growth of the product, website, or app.

In this article, we will see how to integrate google analytics in angular application.

👉 Checkout original article for detailed explanation : Integrate Google Analytics with Angular at NgDevelop

How Google Analytics Track Page Views?

Google analytics provides a tracking code snippet, which we need to put in the HEAD section of each page. When that page is loaded it will trigger an event to capture a page view.

This approach works well for traditional web applications because for each page view tracking code snippet will be loaded and executed.

However, In Single Page Application (SPA) has a single index.html where all other routes are dynamically rendered, because of that that tracking code snippet will be loaded only once. So that the google analytics event will be triggered only once when the initial page is rendered.

So in angular, to capture different route change we need manually trigger page view events.

So let's do it...

Application Setup

In this article, we will not cover angular application development from scratch.

👉 Learn Angular Application Development from Scratch here.

I have created one angular application which has two routes /home and /demo. We will integrate google analytics in this application to capture page views.

We will require the google analytics tracking code to track our application.

Get Google Analytics Tracking Code for Application

  1. Sign in to Google Analytics
  2. Open Admin Panel and click on + Create Property. A property represents your website or app and is the collection point in Analytics for the data from your site or app. You can create multiple properties with one google analytics account.
  3. Select Web or App and fill the required details – Website name, website URL, Industry Category and TimeZone
  4. Now click on the create button to create a property.

Once your property is created it will generate a global site tag(gtag.js) snippet for your application.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING_CODE"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config',[TRACKING_CODE]);
</script>

Note: TRACKING_CODE is your application’s unique tracking code, it will be like UA-XXXXX-X
Now, above tracking code snippet we will install in our application to track page views.

Install Tracking Code Snippet In Angular

Copy and paste the tracking code in head section of index.html as shown below

<!doctype html>
<html lang="en">

<head>
    ... 
    ... 
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING-CODE"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag() { dataLayer.push(arguments); }
        gtag('js', new Date());

        /** Disable automatic page view hit to fix duplicate page view count  **/
        gtag('config', 'TRACKING-CODE', {send_page_view: false});
    </script>

</head>

<body>
    <app-root>App Loading...</app-root>
</body>

</html>

Replace TRACKING-CODE with your tracking code. it will be like UA-XXXXX-X.

Note: gtag(config, TRACKING-CODE) trigger’s an event to capture page view, but in our app, we will capture page views on route change.
So REPLACE gtag(config, TRACKING-CODE) with gtag('config', 'TRACKING-CODE', { send_page_view: false}); So that it doesn’t count page view twice.

Trigger Page View Event On Route Change

Here, We want to trigger the google analytics page view event on route change.

For this, we need to subscribe to the Router.events and on NavigationEnd event we will trigger the google analytics page view event.

We will add router event subscription in app.component.ts. You can also create separate service to handle google analytics page views and events.

We will use gtag function which is globally exported by gtag.js to trigger a google analytics page view event.

...
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

declare const gtag: Function;

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

  ...

  constructor(private router: Router) {
    ...

    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((event: NavigationEnd) => {

      /** START : Code to Track Page View  */

       gtag('event', 'page_view', {
          page_path: event.urlAfterRedirects
       })

      /** END */
    })
  }

}

Great ✨✨✨ We are done with the google analytics setup in angular.

Now open google analytics and test whether it is capturing page views properly or not.

As you can see below, Google Analytics is now showing the number of users and active pages.

Google Analytics Real-Time Snapshot of PageViews

Environment Specific Google Analytics Setup with Angular

Check out the original article: 📄Integrate Google Analytics with Angular for step by step implementation of environment-specific google analytics setup with angular.

Summary

In this article, we have seen the integration of Google Analytics with Angular. We have seen how to trigger the pageview event manually on route change.

I hope you like this article, please provide your valuable feedback and suggestions in the comment section below🙂.

Give your 🤎 with Like and Share. Follow me on twitter @Ankit_NgDevelop

Top comments (0)