I need to add google Analytics to my Angular application. I want to use document.write to insert script. My script is correct and there is no issue there. The problem is that if I put the script in main.js, I think its not rendered as there is no sign of the script in HTML (Inspect in developer tools) and I get an javascript error 'gtag is not defined' My main.js is as under.
Why is script not rendered? Where should I put it?
document.write('<script async src="https://www.googletagmanager.com/gtag/js?id='+environment.googleAnalyticsKey+'"></script>');
const gaElement = `
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
</script>
`;
document.write( gaElement );
AppComponent
export class AppComponent {
constructor( public router: Router ) {
this.router.events.subscribe( event => {
if (event instanceof NavigationEnd ) {
gtag( 'config', environment.googleAnalyticsKey, {'page_path': event.urlAfterRedirects} );
}
} );
}
}