Custom Google Analytics Events with Angular

Ole Ersoy
1 min readFeb 19, 2020

--

Image by narciso1 from Pixabay

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

Load and Configure Google Analytics

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 . 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

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

Responses (1)