Integrating Google Analytics stats with your Angular application is easy. Well, maybe it’s not as easy as it is for non-SPA websites but still it’s possible to do it really quickly.
In this short tutorial, I’m going to show you how you can connect your Angular app to Google Analytics in the 3 easy steps.
Prerequisites and preparation
For the beginning you’ll need 2 things already set up to get started with Google Analytics integration:
- Google Analytics property
- Angular application (in my case it’s Angular 11)
Add the script
The first step is to add the script data into your main application template file meta tags.
Get your property tracking code from the Google Analytics console and delete the
Please remember to replace all of the
G-YOUR-GOOGLE-ID with your own unique property id.
Add it into the
Set up tracking
Now, let’s move into the
AppComponent. Our goal is to subscribe to the router events and track every
NavigationEnd event. It is an Angular Router event that is triggered every time when navigation ends successfully. At this point, we’d like to trigger Google Analytics.
app.component.ts. At first, we’ll declare
Then add this tiny
setUpAnalytics method, which will be invoked on
As you can see, the method contains the
gtag part we previously deleted from the
<script> code snippet.
So, as a result, the
app.component.ts file should look as follows:
Please note that we don’t have to unsubscribe from the
Router events observable.
That’s it. You’re basically ready to start tracking.
The last step is to run your application and check your Google Analytics console.
At this point, you should receive the hits from the users. After running your application and browsing into the. Go into the real-time overview and check if you’re able to see your requests.
You don’t need to deploy your application to achieve that, it should work fine on the local build of your Angular application (
When the console is not receiving any hits
Please remember to turn off the adblocking plugin in the browser to be able to test your setup.
TS linter issues with gtag function variable
If you’ll get linting troubles with that part, you can relax your
Or annotate the
gtag variable with
tslint comment flag.
As you can see, the basic integration of Google Analytics is really easy. With 3 easy steps, you’re ready to go with the default Google Analytics setup, which is enough for the typical use cases.
However, this text doesn’t cover advanced features of Google Analytics (like event goals, etc.). If you need them, please visit Google Analytics docs to learn more about integration.