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
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.
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',
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With