1

I've created a Stackblitz demo of my setup.

This is the index.html GA Script:

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-140430388-3"></script>

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){
    dataLayer.push(arguments)
  }
  gtag('js', new Date());
</script>

And this is the code being executed to trigger events:

  uaClick1() {
    console.log("CLICKED UA 1")
    gtag('event', 'MY_BUTTON_!_CLICK', {
      'event_category': 'BUTTON_CLICK',
      'event_label': 'UA Click 1',
      'value': 'Some custom value 1'   })
  }

  uaClick2() {
    console.log("CLICKED UA 2")
    gtag('event', 'MY_BUTTON_2_CLICK', {
      'event_category': 'BUTTON_CLICK',
      'event_label': 'UA Click 1',
      'value': 'Some custom value 2'   })
  }

When I click the buttons I don't see the events popping up anywhere (Not sure exactly where I should be looking ...) in the GA console.

Thoughts?

Ole
  • 41,793
  • 59
  • 191
  • 359
  • Likely the method has been scoped to a component? Maybe try to define in global js file and import where you want to use it: https://stackoverflow.com/questions/40635259/call-pure-javascript-function-from-angular-2-component – Z. Bagley Feb 19 '20 at 21:11
  • 1
    You need to add `gtag('config', 'GA_MEASUREMENT_ID');` https://developers.google.com/analytics/devguides/collection/gtagjs. Your code is executing as expected and adding items to the layer (add logging before and after in top level gtag function to check for yourself), but isn't configured to your specific ID. – Z. Bagley Feb 19 '20 at 21:36
  • Thanks! I added it and it works now. Do you know if we should be adding the configuration generally in the `index.html` file. One of the tutorial videos I was watching took it out, so as to not fire an analytics event on the main page, as he only wanted to track specific pages, but it looks like we have to add it there? – Ole Feb 19 '20 at 22:34
  • 1
    Since Angular is an SPA and handles all routing internally you will be able to handle it similar to how you have (internally, using methods inside components). You can add the gtag script to your angular.json scripts and then create a service providedIn: 'root' that then manages the gtag calls as well (this is the more 'Angular' way of handling it). As you have it now, it should provide you with the analytics you were hoping for though. Note: +1 for stackblitz demo, made it easy to pinpoint. – Z. Bagley Feb 20 '20 at 12:38

0 Answers0