How to Implement Google Analytics in Angular 8
Adding Google Analytics to your Angular 8 application is the first step toward understanding how users interact with your creation. Instead of guessing, you get direct data on which features they use, where they get stuck, and what content brings them in. This tutorial provides a clean, step-by-step guide to integrate Google Analytics into your Angular project so you can start tracking page views and custom events right away.
What You’ll Need Before You Start
To follow along, you'll need just a couple of things ready to go:
- An existing Angular 8 (or newer) application.
- A Google Analytics account. Specifically, you'll need a "property" set up for your website, from which we can get a Tracking ID.
That's it. Let's get everything connected.
Step 1: Find Your Google Analytics Tracking ID
Your Tracking ID is the unique identifier that tells Google Analytics where to send data from your website. You cannot proceed without it, so let's grab it first.
- Log in to your Google Analytics account.
- Navigate to the Admin section by clicking the gear icon in the bottom-left corner.
- In the ‘Property’ column, click on Tracking Info and then Tracking Code.
- You will see your Tracking ID at the top of the page. It will start with
UA-, followed by a series of numbers (e.g.,UA-12345678-1).
Copy this Tracking ID and keep it handy. You will need it in the next steps.
Step 2: Add the Google Analytics Script to Your Project
The simplest and most reliable way to add Google Analytics to an Angular app is by placing its global site tag (gtag.js) directly into your main index.html file. This ensures the script is loaded once when your application first starts.
Open the src/index.html file in your Angular project and paste the following snippet inside the <head> tag:
<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [],
function gtag(){dataLayer.push(arguments),}
gtag('js', new Date()),
gtag('config', 'YOUR_TRACKING_ID'),
</script>Important: Remember to replace both instances of YOUR_TRACKING_ID with the actual Tracking ID you copied from your Google Analytics account.
By doing this, the gtag() function is now available globally in your application. The initial config call will automatically track the first page view when the user lands on your site.
Step 3: Create an Analytics Service
While gtag() is now globally available, directly calling a global function from your components is not a clean Angular practice. A better approach is to create a service to abstract all your Google Analytics logic. This service can be injected wherever you need it, making your code easier to maintain, test, and read.
Open your terminal in the root of your project and run the Angular CLI command to generate a new service:
ng generate service analyticsThis command creates two files: src/app/analytics.service.ts and src/app/analytics.service.spec.ts.
Now, open src/app/analytics.service.ts. To use the global gtag function without TypeScript throwing errors, you need to declare it. Add this line right below the imports:
declare let gtag: Function,Next, let's create a method inside our AnalyticsService class for tracking custom events. You can add more methods here later for different types of tracking.
import { Injectable } from '@angular/core',
declare let gtag: Function,
@Injectable({
providedIn: 'root'
})
export class AnalyticsService {
constructor() { }
public trackEvent(
eventName: string,
eventCategory: string,
eventAction: string,
eventLabel: string = null,
eventValue: number = null
) {
gtag('event', eventName, {
event_category: eventCategory,
event_label: eventLabel,
event_action: eventAction,
event_value: eventValue
}),
}
}This trackEvent method provides a structured way to send event data to Google Analytics. It takes standard event parameters and calls the global gtag function.
Step 4: Track Page Views on Route Changes
This is the most critical step for any Single-Page Application (SPA) like Angular. After the initial page load, Angular handles navigations internally without full page reloads. This means the default Google Analytics script won't know that the user has navigated to a new "page."
We need to explicitly tell Google Analytics whenever the route changes.
The perfect place to do this is in your root component, app.component.ts. We can listen to router events and fire a page view event whenever a navigation is successfully completed.
First, open src/app/analytics.service.ts again and add a method for tracking page views:
public trackPageView(path: string) {
gtag('config', 'YOUR_TRACKING_ID', { 'page_path': path }),
}Replace 'YOUR_TRACKING_ID' with your ID once more.
Now, open src/app/app.component.ts and inject the Router from @angular/router and your new AnalyticsService. Then, subscribe to the router's events:
import { Component } from '@angular/core',
import { Router, NavigationEnd } from '@angular/router',
import { AnalyticsService } from './analytics.service',
import { filter } from 'rxjs/operators',
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-angular-app',
constructor(private router: Router, private analyticsService: AnalyticsService) {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
this.analyticsService.trackPageView(event.urlAfterRedirects),
}),
}
}Here’s what this code does:
- It gets an instance of Angular's
Routerand ourAnalyticsServicevia dependency injection. - It subscribes to the
router.eventsobservable stream, which emits an event every time something happens with the route. - It uses the RxJS
filteroperator to only listen for theNavigationEndevent. This ensures we only proceed once the new page is fully loaded. - When a
NavigationEndevent occurs, it calls thetrackPageView()method from our service, passing the new URL.
Now, Google Analytics will receive a new page view record every time a user navigates within your app, giving you an accurate picture of their journey.
Step 5: Track Custom Events (Like Button Clicks)
Page views are great, but sometimes you need to track more specific interactions, such as a user clicking a call-to-action button, submitting a form, or watching a video.
Thanks to our AnalyticsService, this is now straightforward. Simply inject the service into any component where you want to track an event and call the trackEvent method.
For example, imagine you have a newsletter signup button in your hero component. Open hero.component.ts:
import { Component } from '@angular/core',
import { AnalyticsService } from '../analytics.service',
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent {
constructor(private analyticsService: AnalyticsService) { }
onSignup() {
this.analyticsService.trackEvent(
'signup',
'Newsletter',
'Submit',
'Top Call-to-Action'
),
// ... your actual signup logic here
}
}And in your hero.component.html template:
<button (click)="onSignup()">Sign Up for Our Newsletter</button>Now, every time a user clicks that button, a custom event with the specified category, action, and label will be sent to Google Analytics. This provides granular insights into user behavior far beyond simple page views.
Step 6: Confirm Everything Is Working
After setting everything up, it's a good idea to verify the data is being sent to Google Analytics correctly. Here are a few ways to do that:
- Browser Developer Tools: Open the Developer Tools (F12 or Ctrl+Shift+I), go to the Network tab, and filter for requests containing "collect." As you navigate through your app and click tracked buttons, you should see new network requests being sent to
www.google-analytics.com. - Google Analytics Real-Time Report: Log in to your Google Analytics account and go to the Realtime > Overview report. You should see yourself as an active user. Navigate to different pages in your application and watch as the active page updates in the report.
- GA Debugger Extension: Install the Google Analytics Debugger extension for Chrome. Once enabled, it prints detailed tracking information into the browser's developer console, making it easy to see exactly what data is being sent.
Final Thoughts
Integrating Google Analytics into your Angular application provides essential visibility into what your users are actually doing. By correctly tracking not only initial page loads but also in-app navigations and key interactions, you replace guesswork with actionable data to improve your user experience.
Once you have data flowing into Google Analytics, the next challenge is making sense of it all. At a certain point, clicking through the GA interface to pull the same reports over and over becomes a headache. It's why we built Graphed. We connect directly to your Google Analytics account so you can build real-time dashboards and reports just by describing what you want to see—like, "Show me traffic sources by conversion rate this month" or "Compare new vs. returning users over the last quarter"—and get the answer back as a clean, live dashboard instantly.
Related Articles
How to Connect Facebook to Google Data Studio: The Complete Guide for 2026
Connecting Facebook Ads to Google Data Studio (now called Looker Studio) has become essential for digital marketers who want to create comprehensive, visually appealing reports that go beyond the basic analytics provided by Facebook's native Ads Manager. If you're struggling with fragmented reporting across multiple platforms or spending too much time manually exporting data, this guide will show you exactly how to streamline your Facebook advertising analytics.
Appsflyer vs Mixpanel: Complete 2026 Comparison Guide
The difference between AppsFlyer and Mixpanel isn't just about features—it's about understanding two fundamentally different approaches to data that can make or break your growth strategy. One tracks how users find you, the other reveals what they do once they arrive. Most companies need insights from both worlds, but knowing where to start can save you months of implementation headaches and thousands in wasted budget.
DashThis vs AgencyAnalytics: The Ultimate Comparison Guide for Marketing Agencies
When it comes to choosing the right marketing reporting platform, agencies often find themselves torn between two industry leaders: DashThis and AgencyAnalytics. Both platforms promise to streamline reporting, save time, and impress clients with stunning visualizations. But which one truly delivers on these promises?