13

Usually including analytics was about pasting their tracking code in the html body, with the property Id and the pageview action. I followed the answer in Tracking Google Analytics Page Views in Angular2 and when doing ng serve it includes correctly the script but then when generating production aot it is not included in the index:

ng build --progress false --aot true -prod -e prod 

What is the best practice to include Google Analytics or other tracking solution with Angular2 Cli?

Thanks in advance

Community
  • 1
  • 1
pdjota
  • 3,163
  • 2
  • 23
  • 33
  • 1
    Following the suggestion in the Angular Cli project, it is need to put the script outside the app-root, I included in the head https://github.com/angular/angular-cli/issues/4451#issuecomment-281628623 – pdjota Feb 22 '17 at 10:37
  • Is that okay if the code is added to an external .js file and linked through .angular-cli.json ? – Saiyaff Farouk Feb 25 '17 at 06:51

3 Answers3

7

You can bundle it with the rest of your scripts using Angular-CLI.

Put the google analytics code in a file named something like google-analytics.js. Make sure you remove the script tags.

Then in your angular-cli.json file, add your google-analytics.jsfile to the scripts property.

Here is an example of what the code would look like in angular-cli.json.

"scripts": [
    "google-analytics.js"
],

This snippet will cause angular-cli to bundle google-analytics into a file named scripts.bundle.js which is loaded at run-time with the ng serve command.

Ty Sabs
  • 209
  • 1
  • 2
  • 10
  • 8
    but how are you loading it only for production? – vlio20 Jul 01 '17 at 08:49
  • 4
    And how can you change the tracking ID if you're deploying to test/acc/prod ? – Richh94 Sep 13 '17 at 10:42
  • 1
    A workaround can be using several apps in .angular-cli.json file ( https://github.com/angular/angular-cli/wiki/stories-multiple-apps ) . Dev app includes file google-analytics.dev.js and Prod app includes google-analytics.prod.js. – Artjoman Sep 27 '17 at 08:59
  • 1
    @vlio20 - Using build config options we can add an additional script for that particular environment also - atleast in Angular 7. – Alok Swain Jun 13 '19 at 12:11
  • angular aot build not working for google analytics, Can u pls help to me – Thulasiram Virupakshi Feb 02 '20 at 15:24
3

Angular Version 7: One way to include some js which is environment-specific is to

  1. save the script at some path: E.g: src/assets/javascripts/google_analytics.js

  2. Then in angular.json find the build config for the specific config (Ref: here) and in the desired environment add an additional scripts array.

  3. ng build --prod will additionally bundle the extra script also. (whatever environment the additional script is added to taking prod for example here)

Below sample uses the production environment for demonstration but this can be done for any environment.

Sample angular.json below. Tested on Angular 7 (Please only refer to the "scripts" key inside the build config, file is heavily modified to show only the relevant part)

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "test": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {},
          "configurations": {
            "production": {
              "scripts": ["src/assets/javascripts/google_analytics.js"]
            }
          }
        }
      }
    }
  },
  "defaultProject": "test"
}
Alok Swain
  • 6,409
  • 5
  • 36
  • 57
3

In angular-cli project you can do it in main.ts - e.g. here we add GA only for production build

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {

    let ga_id = "UA-123456789-1" // google analytics id
    
    document.write(`<script async src="https://www.googletagmanager.com/gtag/js?id=${ga_id}"></script>`);

    const script1 = document.createElement('script');
    script1.innerHTML = `

        // Google Analytics

        window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${ga_id}', {
            'linker': {
            'domains': ['your-domain.com']
            }
        });
    `;
    document.head.appendChild(script1);

    enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err => console.error(err));

The environment.prod.ts must contains field production: true:

export const environment = {
  production: true,
  loginApi: 'https://my-api./v1',
};
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345