0

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} );
        }
    } );
  }
}
user2837961
  • 1,505
  • 3
  • 27
  • 67
  • is there any reason you're not pasting this directly in the `index.html`. this code is static and should be applied to all your pages. – Edward Oct 22 '20 at 17:43
  • The only reason I dont want to put in index.html is because I have environment variable for the google key – user2837961 Oct 22 '20 at 18:00
  • then you should be able to use `{{}}` in the template to reference resolve those environmental variables and make your life simpler. Obviously if there is a reason not to do it, then so be it. otherwse I'd suggest using plain all `document.createElement` as shown here [Link]https://stackoverflow.com/questions/5132488/how-can-i-insert-a-script-into-html-head-dynamically-using-javascript – Edward Oct 22 '20 at 19:21

0 Answers0