Setting up GA4 in AngularJS
The first steps is to setup your properties and data streams for GA4. If you need help with this, follow this walkthrough.
After you have done this and you have your Stream ID and your Measurement ID handy, we can get into the nuts and bolts of doing this in Angular.
- Install the @angular/cli package to create a new angular project.
npm i -g @angular/cli - Then setup a new project using routing (if you prefer)
ng new angular-ga4-project --routing
cd angular-ga4-project - Install the types for gtag.js npm package
npm install @types/gtag.js --save-dev - Then you need to update your tsconfig.app.json file so it sees the new types that you have added.
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": ["gtag.js"]
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
5. Open your index.html file and this is where you need your tag code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo App</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<!-- 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>
</head>
<body>
<app-root></app-root>
</body>
</html>
6. Then add some components and setup your route events:
import { DOCUMENT } from '@angular/common';
import { Component, Inject } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, NavigationEnd, Router, RouterState } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(
private router: Router,
private titleService: Title,
@Inject(DOCUMENT) private document: Document
) {
this.handleRouteEvents();
}
handleRouteEvents() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const title = this.getTitle(this.router.routerState, this.router.routerState.root).join('-');
this.titleService.setTitle(title);
gtag('event', 'page_view', {
page_title: title,
page_path: event.urlAfterRedirects,
page_location: this.document.location.href
})
}
});
}
getTitle(state: RouterState, parent: ActivatedRoute): string[] {
const data = [];
if (parent && parent.snapshot.data && parent.snapshot.data['title']) {
data.push(parent.snapshot.data['title']);
}
if (state && parent && parent.firstChild) {
data.push(...this.getTitle(state, parent.firstChild));
}
return data;
}
}