angulargoogle-analyticsgoogle-tag-managerangular-universalangulartics2

Angular angulartics2 (google analytics) does not update page on route change


I made a site with Angular 8 and Angular Universal and Angular Service Worker. I wanted to add Google Analytics and I found the npm module Angulartics2. I think it partially works, with Google Tag Manager, but it does not recognize the route change. I mean, if I start with the /index page and then I pass to the /exercise page, in my Google Analytics dashboard I still see that the user is using the /index page.

This is the AppModule:

import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FlexLayoutModule } from '@angular/flex-layout';
import { NgxWebstorageModule } from 'ngx-webstorage';
import { Angulartics2Module } from 'angulartics2';
import { Angulartics2GoogleAnalytics } from 'angulartics2/ga';

import { MaterialModule } from './material/material.module';
import { MAT_DATE_LOCALE } from '@angular/material';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { IndexComponent } from './index/index.component';
import { GetSolutionComponent } from './get-solution/get-solution.component';
import { GetSolutionFormComponent } from './get-solution/get-solution-form/get-solution-form.component';
import { GetSolutionProgressComponent } from './get-solution/get-solution-progress/get-solution-progress.component';
import { GetSolutionSolutionComponent } from './get-solution/get-solution-solution/get-solution-solution.component';
import { GetSolutionToggleComponent } from './get-solution/get-solution-form/get-solution-toggle/get-solution-toggle.component';
import { GetSolutionNotesComponent } from './get-solution/get-solution-form/get-solution-notes/get-solution-notes.component';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    IndexComponent,
    GetSolutionComponent,
    GetSolutionFormComponent,
    GetSolutionProgressComponent,
    GetSolutionSolutionComponent,
    GetSolutionToggleComponent,
    GetSolutionNotesComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'unitn-statistica' }),
    HttpClientModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    FlexLayoutModule,
    MaterialModule,
    NgxWebstorageModule.forRoot(),
    AppRoutingModule,
    Angulartics2Module.forRoot(),
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [
    { provide: MAT_DATE_LOCALE, useValue: 'it-IT' },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

This is part of the AppComponent:

import { Angulartics2GoogleTagManager } from 'angulartics2/gtm';

import { AlertService, SnackType, SnackMessage } from './alert/alert.service';

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

  constructor(
    angulartics2GoogleTagManager: Angulartics2GoogleTagManager
    ) {
      angulartics2GoogleTagManager.startTracking();
    }

}

This is the index.html:


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

<head>
  <meta charset="utf-8">
  <title>title</title>
  <base href="/">

  <meta name="Description" content="Login">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">

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

    gtag('config', 'UA-XXXXXXXXXXXX');
  </script>
</head>

<body>
  <app-root></app-root>
  <noscript>Please enable JavaScript to continue using this application.</noscript>
</body>

</html>


Solution

  • In index.html add like this

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

    Don't add gtag('config', 'UA-XXXXXXXXXXXX') in index.html use this in app.component.ts like below

    import { filter } from 'rxjs/operators';
    import  { Router, NavigationEnd } from "@angular/router";
    declare var gtag;
    
    constructor(router: Router) {
    const navEndEvent$ = router.events.pipe(
      filter(e => e instanceof NavigationEnd)
    );
    navEndEvent$.subscribe((e: NavigationEnd) => {
      gtag('config', 'UA-XXXXX', {'page_path':e.urlAfterRedirects}); //gtag added here
    });
    

    }

    This will call the google analytics code every time when route get change.

    You can refer this link https://fluin.io/blog/google-analytics-with-tag-manager-and-angular