How to Add Google Analytics to Angular App
Tracking user behavior in your Angular application doesn't have to be complicated. By adding Google Analytics, you can gain powerful insights into how people interact with your app - what they click, which pages they visit, and where they drop off. This guide will walk you through, step by step, how to integrate Google Analytics (specifically GA4) into your Angular project to track pageviews and custom events correctly.
Why Track Your Angular App with Google Analytics?
Angular creates Single-Page Applications (SPAs), where users navigate between different views or "routes" without full page reloads. This creates a smooth user experience, but it also means standard analytics setups can miss crucial data. A proper integration allows you to:
- Understand User Journeys: See the exact paths users take through your application, from the landing page to conversion.
- Measure Engagement: Track which features are most popular by monitoring interactions like button clicks, form submissions, and video plays.
- Identify Drop-Off Points: Discover where users are leaving your app so you can improve the user experience and increase retention.
- Attribute Conversions: Connect user actions to marketing campaigns to understand your return on investment (ROI).
Without this tracking, you’re essentially flying blind. Let's get it set up so you have the data you need to grow your app.
Step 1: Get Your Google Analytics 4 Measurement ID
Before writing any code, you need a Google Analytics property. We'll be using Google Analytics 4, the latest version. If you have an older Universal Analytics property, the steps for finding your Tracking ID are similar, but GA4 is the current standard.
- 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 Create Property.
- Enter a name for your property (e.g., "My Angular App"), select your reporting time zone and currency, then click Next.
- Provide your business details and click Create.
- Now, you'll set up a data stream. Since we're tracking a web application, choose the Web platform.
- Enter your application's URL and give the stream a name. Click Create stream.
After creating the stream, you'll see a panel with your stream details. Find the Measurement ID, which looks like G-XXXXXXXXXX. Copy this ID and save it somewhere — you'll need it in a moment.
Method 1: The Simple Script Tag Approach (And Its Limitation)
The quickest way to add Google Analytics to any website, including an Angular app, is by adding the global site tag (gtag.js) script to your main HTML file. This method is great for getting started, but it has one major flaw for SPAs.
How to Implement It
Open your Angular project and find the src/index.html file. This is the main shell that loads your entire application. Paste your GA4 tracking code inside the <head> tag.
Your code, with your unique Measurement ID, will look like this:
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [],
function gtag(){dataLayer.push(arguments),}
gtag('js', new Date()),
gtag('config', 'G-XXXXXXXXXX'),
</script>Be sure to replace G-XXXXXXXXXX with your own Measurement ID.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
The Problem
With this setup, Google Analytics will only record one pageview: the initial loading of your application. When a user navigates from /home to /about, Angular changes the view without reloading the page. Since index.html isn't reloaded, the tracking script doesn't run again, and the new pageview is never sent to Google Analytics. Your reports will incorrectly show that every user only visited the home page.
Let's fix this.
Method 2: Manually Tracking Route Changes
To accurately track user navigation in an SPA, we need to tell Google Analytics every time the route changes. We can do this by tapping into Angular's Router and sending a pageview event manually.
First, make sure you've added the gtag.js script from Method 1 to your index.html. This gives us access to the global gtag() function. Now, we'll listen for navigation events.
Step 1: Declare the gtag Function
TypeScript, which Angular uses, needs to know about the global gtag function. Otherwise, it will throw a compilation error. Let’s declare it in the component where we'll track route changes, typically the root app.component.ts.
Open src/app/app.component.ts and add this line near your imports:
declare let gtag: Function,This tells TypeScript: "Don't worry, a function named gtag exists in the global scope, trust me."
Step 2: Listen for Router Events
Next, we inject Angular's Router into our AppComponent and subscribe to its events. We only care about the NavigationEnd event, which fires after a route has successfully changed.
Your app.component.ts should look like this:
import { Component, OnInit } from '@angular/core',
import { Router, NavigationEnd } from '@angular/router',
import { filter } from 'rxjs/operators',
// Let TypeScript know that gtag is a global function
declare let gtag: Function,
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.events.pipe(
// We only want to track successful navigation events
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
// When a new page is navigated to, send a pageview event to Google Analytics
gtag('event', 'page_view', {
page_path: event.urlAfterRedirects,
page_title: 'Your Page Title', // optional, you can update this dynamically
page_location: window.location.href
}),
}),
}
}In this code, we filter the router's events to listen only for NavigationEnd. When it fires, we call gtag() and pass in a page_view event, including the new URL path (event.urlAfterRedirects). Now, every route change will be logged in Google Analytics as a new pageview.
Method 3: A Cleaner Approach with an npm Package
While the manual method works perfectly fine, it can feel a bit messy. For a cleaner, more modular solution, you can use a dedicated package like angular-gtag. This package wraps the gtag.js logic in an Angular-native way, making it easy to manage page tracking and custom events.
Step 1: Install the Package
In your project's terminal, run:
npm install angular-gtagStep 2: Configure the Module
Next, you need to import and configure the module in your main app.module.ts. This tells your entire application how to use the Google Analytics service.
Edit src/app/app.module.ts:
import { NgModule } from '@angular/core',
import { BrowserModule } from '@angular/platform-browser',
import { AppRoutingModule } from './app-routing.module',
import { AppComponent } from './app.component',
// Import GtagModule
import { GtagModule } from 'angular-gtag',
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
// Add the GtagModule to your imports and configure it
GtagModule.forRoot({ trackingId: 'G-XXXXXXXXXX', trackPageviews: true })
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }Replace G-XXXXXXXXXX with your Measurement ID. The trackPageviews: true option automatically handles listening for router events and sending pageviews for you. With this setup, you've replicated all the work from Method 2 with just a few lines.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Step 3: Track Custom Events
The benefit of using this package is easier custom event tracking. For example, to track a "Sign Up" button click, in your component's TypeScript file:
import { Component } from '@angular/core',
import { Gtag } from 'angular-gtag',
@Component({
selector: 'app-signup-button',
template: `<button (click)="onSignUp()">Sign Up Now</button>`,
})
export class SignupButtonComponent {
constructor(private gtag: Gtag) {}
onSignUp() {
// ... your signup logic here ...
// Send an event to Google Analytics
this.gtag.event('sign_up_completed', {
event_category: 'conversion',
event_label: 'Header Sign Up Button'
}),
}
}You’ll see events like this appear in your Google Analytics under Engagement > Events. This measures what users are actually doing beyond just visiting pages.
Verifying Your Implementation
After implementing one of these methods, you should confirm it works:
- GA Realtime Reports: Go to your Google Analytics dashboard, navigate to Realtime, and perform some navigation in your app. You should see activity here, including pageviews for different routes.
- Browser DevTools: Open your browser's developer console, go to the Network tab, filter requests for "collect," and observe requests made to Google Analytics when you change routes.
- Google Tag Assistant: Use this Chrome extension from Google to validate your tags are installed and firing correctly.
Final Thoughts
In this guide, you've learned everything from basic script implementation to a more robust, Angular-friendly package for tracking events. With proper Google Analytics setup, you can now collect meaningful data about user behavior in your Single-Page Application, helping you make informed decisions to improve and grow your product.
Once your Google Analytics data starts rolling in, the next challenge is making sense of it all. Instead of getting stuck in complex GA reports, we built Graphed to help you get answers instantly. Connect your Google Analytics account in seconds and ask questions like "Show me a chart of my top landing pages by conversion rate" or "Compare user traffic from last month to this month," and Graphed automatically creates beautiful, real-time dashboards for you.
Related Articles
Facebook Ads for HVAC Companies: The Complete 2026 Strategy Guide
Learn how to run high-converting Facebook ads for HVAC companies in 2026. This guide covers targeting, creative strategies, and proven campaigns that drive real leads.
Facebook Ads for Florists: The Complete 2026 Strategy Guide
Learn proven Facebook advertising strategies for florists in 2026. Target the right audience, create compelling visuals, and optimize your ad budget for maximum ROI.
Facebook Ads For Dental Practices: The Complete 2026 Strategy Guide
Learn how to effectively use facebook ads for dental practices to attract new patients to your dental practice. This comprehensive 2026 guide covers targeting, budgeting, creative strategies, and ROI expectations.