Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include Google Analytics in Angular Cli application

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

like image 638
pdjota Avatar asked Feb 22 '17 10:02

pdjota


People also ask

How do I add Google Analytics to Angular JS 7?

How to add Google Analytics to your Angular app (the hard way) The first step is to go into the settings for your Google Analytics property and find the Global site tag . You want to copy the global site tag into the head of your index. html file.


1 Answers

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',
};
like image 55
Kamil Kiełczewski Avatar answered Sep 19 '22 23:09

Kamil Kiełczewski