Custom Google Analytics Events with Angular | Task

Ole Ersoy
Apr - 14  -  2 min

Scenario

We have a button that when clicked should trigger a custom Google Analytics Tag Manager event.

<button (click)="trackMe()">Track this Click</button>

Approach

First setup a property in Google Analytics and obtain the tracking code for it.

It will give you something like this when clicking on Tracking Info > Tracking Code in the admin area of Google Analytics. It should look like this:

<!-- Global site tag (gtag.js) - Google Analytics -->
<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());
gtag('config', 'UA-140430388-3');
</script>

Add the script to the head tag in index.html of your Angular project.

Track Click Events

First declare gtag in app.component.ts. This lets Typescript know that the gtag function has been defined elsewhere:

declare var gtag

Place the following method in app.component.ts

trackMe() {
gtag('event', 'TRACK_ME_BUTTON_CLICKED', {
'event_category': 'BUTTON_CLICK',
'event_label': 'Track Me Click',
'value': 'Put a value here that is meaningful with respect to the click event'   })
}

And bind it to the button in app.component.html:

<h1>Google Analytics Demo</h1>
<button (click)="trackMe()">Track Click</button>

To see the click events look at the Events tab of the Realtime Google Analytics panel.

Demo