February 15, 2017

Tutorial: Angular 2 & Google Analytics with Event tracking

In this post, I’ll show you how to add Google Analytics to an Angular 2 project. There is really no need to use an extra library for including Analytics since the setup is really simple. I will use the Angular CLI to create a new project and add a sample routing between site-a and site-b. The pageviews will be tracked and transferred to Google Analytics. In addition, I’ll show how to submit evens to Analytics. For this purpose a service will be implemented. The full source code is published at Github. For each step there is a single commit, which is linked in the respective headline.



I will start by creating a new project through the Angular CLI. If you already have a project then you can of course also use this.



Step 1: Add Typings for Google Analytics – (Code)

Since we want to use TypeScripts typing-features we have to install the required typings via npm.



Step 2: Add Example Routes – (Code)

Since the application is currently still empty, I will now create two new components (site-a and site-b). If you are working in an existing project, you can skip until step 4.



Step 3: Routing – (Code)

Now I must integrate the two created components with the routing. To do this, I first create the route configuration and then add the router-outlet to the AppComponent. Finally, the RouterModule must be imported in the AppModule. The route configuration will also be applied.



Step 4: Add Google Analytics Tracking Code – (Code)

Now it’s time to include Analytics tracking code. Please note that we are in a single page application. Therefore, we must send the pageview manually. To do this, we add the tracking code to the index.html file and then remove the last line since it is responsible for transmitting the pageview.

To navigate at all, I have to add  two links to my example, so that the view can be switched between site-a and site-b component. In order to be able to capture the pageviews manually, we will catch the router events in the AppComponent and forward them to Google Analytics.

Make sure to paste your own tracking code to the index.html and to remove the ga('send', 'pageview'); line!

That’s it already! Now the pageviews are sent to Google Analytics.



Step 5: Event Tracking with Angular – (Code)

In a real application, we can understand the user behavior even better if we submit some events to Google Analytics. In our example we will install a button. When the user clicks on it, an event is sent to Analytics. In order to make the re-usability possible, I have stored the required code in a service. We will add a button to our app components template and implement the method submitEvent in the related TypeScript code.

Congratulations, we have already realized an event tracking with Angular 2! Check if everything works as expected by using the real time overview in Google Analytics.




Working Page View Tracking:

Working Event Tracking:

Can Kattwinkel

Entwickler bei thecodecampus

Comments (23)

  1. Pedro says:

    Thank you, Can!
    Most helpfull; works ike a charm!

  2. Abdeali says:

    Thanx the Code works …. I didnt try the event Catching yet

  3. Vinay says:

    thank you sir absolutely helpful

  4. Esrhim says:

    Thanks for the post, it’s very useful.

    Just one note, if you don’t use Angular CLI, it complains using wepback: “Cannot find name ‘ga’.”. It should be fine to include below code into the app component, and declare ga as ambient function.

    // Declare ga function as ambient
    declare let ga: Function;

    1. Broc says:

      Just add the reference path at the top of the file:


    2. Ron says:

      And into google-analytics-events.service.ts

    3. sejin says:


      declare let ga: Function;

      1. Leticia says:

        I do not understand what you mean by adding the UA-ID of your tracking code

  5. Daniel Furze says:

    This is awesome! Thanks 😀 works a treat.

  6. Lukasz says:

    Good one!
    Thank you very much!

  7. Eric says:

    Would this work with angular 4?

    1. Carolina says:

      Yes, It worked for me, I just had to declare “ga” to the app comp and the service

      declare let ga: Function;

      This tutorial also helped me to add Facebook pixels, thank you 🙂

  8. Mathias says:

    You show the code in the body
    But it would not work for me until I placed it where Google suggested
    At the inside bottom of the head tag

    Thanks for putting this online!

  9. Gal says:

    Thank you very much for this guide! Very helpful 🙂

    BTW, Angular CLI will also trigger the “Cannot find name ‘ga’.” bug. The following line should be added *before* the deceleration (before @Component in app.component; before @Injectable in the service):

    declare let ga: Function;

    1. Dave Vaughan says:

      Thanks heaps mate, was getting disheartened when it wasnt playing ball.

  10. IG says:

    If you struggle, use
    declare let ga: any;

  11. AngularCoder says:

    Our Angular 4 application works fine on web. However when viewed on mobile, we get the below error on some mobiles.
    Uncaught ReferenceError: ga is not defined

  12. soywod says:

    Nice share 🙂
    I have some improvements for you here. In my code, I didn’t subscribe to router events from the app constructor, but from the ngOnInit method instead. I also saved the subscription, so that I can unsubscribe from the ngOnDestroy method. See the result here : https://github.com/soywod/lexicoon/blob/master/src/app/app.component.ts

  13. Thaks, but not working here:.

    ERROR ReferenceError: ga is not defined
    at GoogleAnalyticsService.webpackJsonp…/../../../../src/app/services/google-analytics/google-analytics.service.ts.GoogleAnalyticsService.emitEvent

    any one can help me? please!

  14. Unni says:

    Good Share Can!!
    Thanks @soywod too for ngOnDestroy & unsubscribe.

    Quick question, how to add GA on some hyperlinks clicks in HTML files!


  15. Remi Sture says:


    Is there a way to have environment specific UA-ID’s in the snippet you have defined in index.html?

    For instance ‘UA-XXXa’ for prod, and ‘UA-XXXb’ for dev.

    1. Can Kattwinkel says:

      It would be possible if you use angular cli where you have different environment files and you can define the ua-id there as variable.

      However I would not recommend to do that. Since you have to duplicate many things in Analytics across all properties. Like Conversions, segments and so on. The correct approach is to use views in Google Analytics!


      Filter for localhost url for dev environment, prod url and so on.

  16. ritesh says:

    I am unable to print the event in google analytics event console .though i am using the same code which is above mentioned in service file in angular 4 ,and also i would i like to thanks as my app is able to print the active components in analytics overview thanks a ton

Leave a Reply

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