monitor with html tag

Add Google Tag Manager to an Angular application

First add the noscript tag to handle cases where javascript is turned off and you still want to capture analytics data.

<!-- Google Tag Manager (noscript) -->
<noscript>
  <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden">
  </iframe>
</noscript>
<!-- End Google Tag Manager (noscript) -->

Next add the Google Tag Manager script as far up in the head of your index.html as possible

<script>
window.dataLayer = window.dataLayer || [];
</script>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
	new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
	j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
	'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
	})(window,document,'script','dataLayer','GTM-XXXXXX');
</script>
<!-- End Google Tag Manager -->

Now the GTM will be ready to use

The DataLayer

You can see in the above code snippet that the dataLayer is setup before the GTM script, this is necessary for it to work correctly. In your root component, probably app.component.ts, setup GTM to run in the Angular app.

private setupGoogleTagManager() {
  window['googleTagManager']("GTM-XXXXXX")
  
  this.googleTagManagerIframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(
    "https://www.googletagamanager.com/ns.html?id=GTM-XXXXXXX"
  )
}

// then in the constructor

this.setupGoogleTagManager()

The Google Tag Manager use a special data layer variable called event that is used by JavaScript event listeners to fire tags when a user interacts with website elements. Events are fired by pushing the event and event name onto the data layer queue. This is vanilla JavaScript where where we initialize an array and then push an object into it.

window.dataLayer.push({'event': 'event_name'})

Now in the component where we want to fire a click event for example

handleEventWeWantToCaptureClick(): void {
  this.setupGoogleTagManagerForEventClicks()
}

private setupGoogleTagManagerForEventClicks(): void {
  window.dataLayer.push({'event': 'clickEventYouWantToCapture'})
}

Then in the component HTML

<a>
  class="cool-link-to-track"
  href="https://example.com"
  (click)="handleEventWeWantToCaptureClick()"
  Example link
</a>

That should be it. Good luck!


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *