Single-page application frameworks and libraries can be a blessing for developers but a pain when it comes to properly implementing tracking and analytics.
If you’ve ever worked with Google Analytics, you would have encountered the global site tag — or gtag.js. Google tells you to pass this code as the first item in the <head> area of the web page you want to track.
But when you’ve only got one page, as single-page applications built-in frameworks like Angular do, the copy and paste solution won’t work the way you need it to work.
How Angular Works
Components are the things that makeup parts of the visual jigsaw. While you may be navigating away from a particular view and the link in the address bar dynamically changes to match, you are still on the same root page.
This is because the browser doesn’t refresh your page and there’s no new page loaded. It’s still the same page — just a different view and the basic implementation of Google’s Analytics tag doesn’t know this.
It Starts With the Copy-Paste gtag.js Code
There are two versions of tracking through Google Analytics — ga and gtag. ga is the older and depreciated version, with Google pushing for gtag.js implementation instead.
To start, you’ll need to go into your Google Analytics panel and find the copy-paste code. You’ll need to copy this code, put it in the <head> section as suggested, minus the gtag('config', 'xx-xxxxx-xxx'); part in the snippet.
This little code snippet simply makes the gtag.js library available for your application’s consumption. gtag('config', 'xx-xxxxx-xxx'); function executes the page view portion of your webpage.
The gtag() function is what we’ll be dealing with for anything Google Analytics related.
Router Events Is the Secret to Your Angular Sauce
Angular has several event handling methods which can be used to access certain information. For Google Analytics, what we’re interested in is the URL a user has navigated to.
To extract this information, we can use navigationEnd method to access a property called urlAfterRedirects. This property contains the / portion of your routing URL.
To use navigationEnd, you’ll need to import it and subscribe the event to call gtag() when something happens. You’ll also need to give your Angular component access to gtag by declaring it as a Function.
For code efficiency purposes, you can place all this in the app.component.ts file as it is the first file that gets called and loads at the top level of everything that eventually follows.
In short, your code should look something like this:
Event tracking adds another layer of data to your Analytics statistics. Its implementation, however, is less laid back than page views and will require a little intervention to get the right data to Google’s free platform.
This post is for paying subscribers only
Sign up now and upgrade your account to read the post and get access to the full library of posts for paying subscribers only.