Google Analytics (gTag) and Angular

Adding Google Analytics (gTag) to an Angular 8 application

Posted on November 6, 2019

Tags:

Angular

Adding the basics of Google Analytics to your Angular application is a simple process.

Firstly, add the following code to the <head> tag in your index.html file.

<script async src="https://www.googletagmanager.com/gtag/js?id=MY-TAG-ID"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
</script>

We then need to update your app.component file with the following. This will pass the route/page name to Google Analytics on route change events.

The important bits here are declaring the gtag variable, importing the Router module and subscribing to the Router events in the constructor.

import {Component} from '@angular/core';
import {Router, NavigationEnd} from '@angular/router';
declare let gtag;

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    constructor(private _router: Router) {
        this._router.events.subscribe(event => {
            if (event instanceof NavigationEnd) {
                gtag('config', 'MY-TAG-ID',
                    {
                        page_path: event.urlAfterRedirects
                    }
                );
            }
        });
    }
}