Google Analytics (gTag) and Angular

Adding Google Analytics (gTag) to an Angular 8 application

Posted on November 6, 2019



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=""></script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

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;

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