Track Google Analytics on Angular2


Nowadays Single Page (Web) Application (SPA) is taking over traditional full post-back website. Google Analytics standard tracking code is though yet to support SPA website. We then have to manually implement to track route change.

Google Analytics , at the moment, provides this kind of tracking js code.

(function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,’script’,’https://www.google-analytics.com/analytics.js’,’ga’);

ga(‘create’, ‘UA-123456-1’, ‘auto’);
ga(‘send’, ‘pageview’);

Per my previous post – Passing javascript global variable to Angular2 (Typescript). We can archive by sending ga object to Angular2. You can choose either approach 1 or 2.

Then at the root component, AppComponent in my previous post, update constructor as follow.

constructor(private router: Router, @Inject(‘ga’) ga:any) {
router.subscribe((val) => {
ga(‘send’, ‘pageview’, { page: val });
});
}

We need to inject router to the constructor and inject ga variable from javascript also.

router has ability to subscribe route change event. We make use of it and call ga function to post tracking to Google Analytics. val parameter is path of target route.

Updated version of Angular2 probably also updated the router class. Please try following if you use a newer version of Angular2.

router.changes.subscribe((val) => {
ga(‘send’, ‘pageview’, { page: val });
});

Then you can use Live overview of Google Analytics to validate if it works properly. Enjoy 🙂

Tagged , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: